Django - 如何显示保存在ImageField中的照片? [英] Django - How can I display a photo saved in ImageField?
问题描述
我已经在圈子里玩了几个小时。
我有一个UserProfile模型,具有 profile_pic ImageField。我保存了用户照片,现在我想显示它,但没有任何作用。我通过文档,SO,谷歌,没有结果。
我上传了一张照片,我可以看到该url被保存在数据库中。
这是我有的:
I've been going around in circles for hours with this.
I have a UserProfile model with profile_pic ImageField. I saved the user photo and now I want to display it, but nothing works. I went through docs, SO, google, with no result.
I uploaded a photo, and I can see that the url was saved in the database.
This is what I have:
# models.py
class UserProfile(models.Model):
...
title = models.CharField()
about_me = models.CharField()
profile_pic = models.ImageField(upload_to=content_file_name, blank=True)
# views.py
def user_details(request):
if request.method == 'POST':
form = UserProfileForm(request.POST, request.FILES, instance=request.user.get_profile())
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
form = UserProfileForm(instance=request.user.get_profile())
return render_to_response('user_details.html',
{'user': request.user, 'form': form},
context_instance=RequestContext(request))
# user_details.html
{% for field in form %}
{% if field.name != "profile_pic" %}
<!-- display regular fields -->
{{ field.label_tag }}{{ field }}
{% else %}
<!-- display the user photo -->
<img src="{{ MEDIA_URL }}{{ field.url }}" />
{% endif %}
{% endfor %}
当我查看所呈现的HTML的来源,我看到的是MEDIA_URL(即media /),而不是照片网址。如果我用{{field}}替换{{field.url}},我得到带有Currently标签的URL,一个Clear复选框和一个可以更改图像的选项。但是我看不到图像本身。
任何人都可以建议我做错了什么?
When I view the source of the rendered HTML, all I see is the MEDIA_URL (ie 'media/') but not the photo url. If I replace {{ field.url }} with {{ field }} I get the url with the label "Currently", a "Clear" checkbox and an option to change image. But I cannot see the image itself.
Can anyone suggest what am I doing wrong?
推荐答案
对不起我没有非常注意字段
的上下文。从for循环中获得的field是一个专门的包装器,其中包含有关该字段的其他数据,用于构建表单。它不是模型本身的领域,只是为了表单的目的而表示。
Sorry, I didn't pay close enough attention to the context of field
. The "field" you get from the for loop is a specialized wrapper that includes other data about the field for the purposes of constructing the form. It's not the field on the model itself, just a representation of it for the purposes of the form.
要获取当前值 profile_pic
,您需要使用表单的实例:
To get the current value of profile_pic
, you need to use the form's instance:
<img src="{{ form.instance.profile_pic.url }}" />
{{MEDIA_URL}}
使用 url
属性,因为它会自动追加 MEDIA_URL
。
{{ MEDIA_URL }}
is unnecessary when using the url
attribute, since it automatically appends MEDIA_URL
.
这篇关于Django - 如何显示保存在ImageField中的照片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!