当用户为我的应用程序注册时,当用户到达配置文件页面时,我会收到这个错误。
The 'image' attribute has no file associated with it.
Exception Type: ValueError
Error during template rendering
In template C:\o\mysite\pet\templates\profile.html, error at line 6
1 <h4>My Profile</h4>
2
3 {% if person %}
4 <ul>
5 <li>Name: {{ person.name }}</li>
6 <br><img src="{{ person.image.url }}">
Traceback Switch back to interactive view
File "C:\o\mysite\pet\views.py" in Profile
71. return render(request,'profile.html',{'board':board ,'person':person})我认为这个错误是因为我的模板需要一个图像,并且看到他刚刚注册,他不能添加一个图像,除非他转到编辑页面并添加一个页面,然后他可以访问配置文件页面。
我的profile.html
<h4>My Profile</h4>
{% if person %}
<ul>
<li>Name: {{ person.name }}</li>
<br><img src="{{ person.image.url }}">
</ul>
{% endif %}我在views.py的个人资料功能
def Profile(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:LoginRequest'))
board = Board.objects.filter(user=request.user)
person = Person.objects.get(user=request.user)
return render(request,'profile.html',{'board':board ,'person':person})我尝试了这个解决方案,创建了Person对象的2个实例,并在我的模板中使用if将它们分开,但是它没有成功。
<h4>My Profile</h4>
{% if person %}
<ul>
<li>Name: {{ person.name }}</li>
</ul>
{% endif %}
{% if bob %}
<ul>
<br><img src="{{ bob.image.url }}">
</ul>我对Profile函数的解决方案
def Profile(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:LoginRequest'))
board = Board.objects.filter(user=request.user)
person = Person.objects.get(user=request.user)
bob = Person.objects.get(user=request.user)
return render(request,'profile.html',{'board':board ,'person':person,'bob':bob})我一直在阅读内置模板标记和过滤器的文档,我认为这里的一个解决方案是使用(和)模板标记,但我似乎不能正确地使用它。
如何配置此模板以使图片成为选项。如果他们没有照片,离开它,但显示人名。
谢谢你对我的照顾
发布于 2013-03-10 12:54:27
bob和person是同一个对象,
person = Person.objects.get(user=request.user)
bob = Person.objects.get(user=request.user)这样你就可以用人来做了。
在模板中,首先检查是否存在image,
{% if person.image %}
<img src="{{ person.image.url }}">
{% endif %}发布于 2013-05-20 07:26:59
最好的方法是在模型类中添加一个助手方法,如下所示:
@property
def image_url(self):
if self.image and hasattr(self.image, 'url'):
return self.image.url并使用default_if_none模板筛选器提供默认url:
<img src="{{ object.image_url|default_if_none:'#' }}" />发布于 2019-11-09 01:54:50
我亲爱的朋友,其他解决方案是好的,但还不够,因为如果用户没有配置文件图片,您应该很容易地显示默认图像(不需要迁移)。因此,您可以按照以下步骤操作:
将此方法添加到您的人员模型中:
@property
def get_photo_url(self):
if self.photo and hasattr(self.photo, 'url'):
return self.photo.url
else:
return "/static/images/user.jpg"您可以使用任何路径(/media、/static等)但是,不要忘记将默认的用户照片作为user.jpg放到您的路径中。
在模板中更改代码,如下所示:
<img src="{{ profile.get_photo_url }}" class="img-responsive thumbnail " alt="img">https://stackoverflow.com/questions/15322391
复制相似问题