2016-10-18 41 views
0

我已经尝试了几种关于如何从模型中检索图像但没有运气的方法,这是我目前所处的位置。我想要显示图片,当用户点击图片时,会打开一个显示项目详情的模式。Django显示模型中的照片

models.py

class Project(models.Model): 
    author = models.ForeignKey('auth.User') 
    title = models.CharField(max_length=200) 
    client = models.CharField(max_length=200) 
    date = models.DateField(timezone.now()) 
    service = models.CharField(max_length=200) 
    info = models.TextField() 
    photo = models.ImageField(upload_to='ports/static/img/', 
          default='ports/static/img/port_photo.png', 
          height_field='photo_height', 
          width_field='photo_width',) 
    photo_height = models.PositiveIntegerField(blank=True, default=900) 
    photo_width = models.PositiveIntegerField(blank=True, default=650) 
    created_date = models.DateTimeField(
    default=timezone.now) 
    published_date = models.DateTimeField(
    blank=True, null=True) 


的index.html

<section id="portfolio"> 
    {% for project in projects %} 
     <div class="row"> 
      <div class="col-lg-12 text-center"> 
       <h2>Portfolio</h2> 
       <hr class="star-primary"> 
      </div> 
     </div> 
     <div class="row"> 
      <div class="col-sm-4 portfolio-item"> 
       <a href="#portfolioModal1" class="portfolio-link" data-toggle="modal"> 
        <div class="caption"> 
         <div class="caption-content"> 
          <i class="fa fa-search-plus fa-3x"></i> 
         </div> 
        </div> 
        <img src="{{ projects.photo.url }}" class="img-responsive" alt=""> 
       </a> 
      </div> 
     </div> 
    </div> 
    {% endfor %} 
</section> 

views.py

from django.shortcuts import render 
from .forms import ContactForm 
from django.utils import timezone 
from .models import Project 
# Create your views here. 


def index(request): 
    form_class = ContactForm 
    projects = Project.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') 
    return render(request, 'ports/index.html', {'form': form_class, 'projects': projects}) 

回答

1

看看你img标签。在src属性中,您正在使用{{ projects.photo.url }}。因此,您无法从查询集中获取图像,只能从Project模型的对象中获取图像。使用{{ project.photo.url }}

+0

感谢这么多,我也不得不改变 –

+0

.... 照片= models.ImageField(upload_to = '端口/静态/ IMG /', 默认= '端口/静态/ IMG/port_photo.png' , height_field = 'photo_height', width_field = 'photo_width',) –

+0

到 相片= models.ImageField(upload_to = '静态/ IMG /', 默认= '静态/ IMG/port_photo.png', height_field = 'photo_height', width_field ='photo_width',) 并迁移数据库,然后重新上传图像。 –