当用户为我的应用程序注册时,当用户到达配置文件页面时,我会收到这个错误。
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})我一直在阅读内置模板标记和过滤器的文档,我认为这里的一个解决方案是使用(和)模板标记,但我似乎不能正确地使用它。
如何配置此模板以使图片成为选项。如果他们没有照片,离开它,但显示人名。
谢谢你对我的照顾
发布于 2020-07-28 08:01:51
还可以使用Python3内置函数getattr创建新属性:
@property
def image_url(self):
"""
Return self.photo.url if self.photo is not None,
'url' exist and has a value, else, return None.
"""
if self.image:
return getattr(self.photo, 'url', None)
return None并在模板中使用此属性:
<img src="{{ my_obj.image_url|default_if_none:'#' }}" />https://stackoverflow.com/questions/15322391
复制相似问题