[英]Django display a photo from a model
I've tried several of methods on how to retrieve an image from a model with no luck, this is where I'm at so far. 我已经尝试了几种方法来从模型中检索图像而没有运气,这是我到目前为止的工作。 I'd like to have the image show and when the user clicks on it, it opens a modal showing a projects detail.
我想要显示图像,当用户单击它时,它将打开一个显示项目详细信息的模式。
models.py 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 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 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})
Look at your img
tag. 查看您的
img
标签。 In the src attribute, you are using {{ projects.photo.url }}
. 在src属性中,您正在使用
{{ projects.photo.url }}
。 So, you cannot get image from a queryset, you can only do so from an object of Project
model. 因此,您不能从查询集获取图像,而只能从
Project
模型的对象获取图像。 Use {{ project.photo.url }}
使用
{{ project.photo.url }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.