我将向用户上传图片,并将其显示在模板中。
我安装了枕头,并添加了@property,但问题仍未解决。
my requirements.tct includes:
Django==2.2
django-crispy-forms==1.7.2
Pillow==6.0.0
pytz==2019.1
sqlparse==0.3.0
in models.py
class Melk(models.Model):
city = models.CharField(max_length=50)
image = models.ImageField(upload_to = 'pic_folder', blank = True)
def __str__(self):
return self.city
@property
def image_url(self):
if self.image and hasattr(self.image, 'url'):
return self.image.url
in template
<div class="page-header">
{% if show_mine %}
<ul>
<div class="row">
{% for show in show_mine %}
<div class="col-lg-4 mb-4">
<li>
{{ show.image.url | default_if_none:'#' }}
{{ show.city }}
</li>
</div>
{% endfor %}
</div>
</ul>
{% endif %}
</div>
程序在没有图像字段的情况下可以正常运行。我希望用户可以在模板中看到他上传的图像。
错误是:
ValueError at /users/home/
The 'image' attribute has no file associated with it.
Request Method: GET
Request URL: http://127.0.0.1:8000/users/home/
Django Version: 2.2
Exception Type: ValueError
Exception Value:
The 'image' attribute has no file associated with it.
Exception Location: C:\Users\Student\Desktop\myproject\lib\site-packages\django\db\models\fields\files.py in _require_file, line 38
Python Executable: C:\Users\Student\Desktop\myproject\Scripts\python.exe
Python Version: 3.7.3
答案 0 :(得分:0)
问题是由于没有文件链接到ImageField,因此将 {{show.image.url}} 置于if条件下,
{% if show.image %}
{{ show.image.url }}
{% endif %}
验证文件链接是否正常工作。您可以在ImageField中添加默认值,
avatar = models.ImageField(upload_to='avatars/', null=True, blank=True, default='/static/img/default-user.png')
或者您可以更改自定义属性,例如
@property
def image_url(self):
if self.image:
return self.image.url
return '#'