Django“ image”属性没有与之关联的文件

当用户注册我的应用程序时,当他到达个人资料页面时,我收到了这个错误。

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})

我认为这个错误发生,因为我的模板需要一个图像,看到他刚刚注册,他不能添加一个图像,除非他去编辑页面,并添加一个页面,然后他可以访问个人资料页面。

我的个人资料 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})

我尝试了这个解决方案,创建了一个2实例的 Person 对象,并在我的模板中使用一个 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>

我对配置文件函数的解决方案

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})

我一直在阅读有关内置模板标签和过滤器的文档,我认为这里的解决方案是使用(和)模板标签,但我似乎不能正确使用它。

如何配置此模板使图片成为一个选项。如果他们没有图片留下它,但显示人名。

谢谢你帮我

102027 次浏览

bob and person are the same object,

person = Person.objects.get(user=request.user)
bob = Person.objects.get(user=request.user)

So you can use just person for it.

In your template, check image exist or not first,

{% if person.image %}
<img src="\{\{ person.image.url }}">
{% endif %}

The better approach which would not violate DRY is to add a helper method to the model class like:

@property
def image_url(self):
if self.image and hasattr(self.image, 'url'):
return self.image.url

and use default_if_none template filter to provide default url:

<img src="\{\{ object.image_url|default_if_none:'#' }}" />

Not exactly what OP was looking for, but another possible solution would be to set a default value for ImageField:

 class Profile(models.Model):
# rest of the fields here
image = models.ImageField(
upload_to='profile_pics/',
default='profile_pics/default.jpg')

My dear friend, others solvings are good but not enough because If user hasn't profile picture you should show default image easily (not need migration). So you can follow below steps:

Add this method to your person model:

@property
def get_photo_url(self):
if self.photo and hasattr(self.photo, 'url'):
return self.photo.url
else:
return "/static/images/user.jpg"

You can use any path (/media, /static etc.) but don't forget putting default user photo as user.jpg to your path.

And change your code in template like below:

<img src="\{\{ profile.get_photo_url }}" class="img-responsive thumbnail " alt="img">

You can also use the Python 3 built-in function getattr to create your new property:

@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

and use this property in your template:

<img src="\{\{ my_obj.image_url|default_if_none:'#' }}" />

you have two choices :

  • first one:

in the model field try to put a default image value , like this :

PRF_image = models.ImageField(upload_to='profile_img', blank=True, null=True , default='profile_img/925667.jpg')
  • the second one (recommended) :

add a custom method inside your class model like the following , to return PRF_image url if exist or return empty string if not :

PRF_image = models.ImageField(upload_to='profile_img', blank=True, null=True )


@property
def my_PRF_image(self):


if self.PRF_image :
return self.PRF_image.url
return ''

and inside your template you can use :

\{\{ your_object.my_PRF_image }}

i hope this helpful .

Maybe this helps but my database didn't save on of the pictures for the object displayed on the page.

As that object in models.py has blank=False and also I am looping through object, it constantly gave an error until I added a replacement picture in the admin for the database to render.

This error also arises when any one or more items doesn't have an image added and the rest items do. To fix this:

class Product(models.Model):
pname = models.CharField(max_length=30)
price = models.IntegerField()
img = models.ImageField(null = True,blank = True)
def __str__(self):
return self.pname
@property
def imageURL(self):
try:
url = self.img.url
except:
url=''
return url

Many way to solve this issue

Try below code

models.py # under Person class

@property
def imageURL(self):
if self.image:
return self.image.url
else:
return 'images/placeholder.png'

html file

<img src="{% static person.imageURL %}" class="thumbnail" />