【发布时间】:2020-12-20 00:01:33
【问题描述】:
我正在尝试创建一个单页应用程序,您可以在其中将图片上传到数据库,并将其显示在索引页面中。
我无法显示照片,即使在 html 部分中调用 {{post.picture}} 时它返回图片的路径
媒体设置:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
查看:
from random_tasks_app import forms
from random_tasks_app.models import Post
def index(request):
posts = Post.objects.all()
if request.method == 'POST':
form = forms.UploadImageForm(request.POST, request.FILES)
if form.is_valid():
form.save()
else:
form = forms.UploadImageForm()
return render(request, 'index.html', {'form': form, 'posts' : posts})
型号:
from django.db import models
class Post(models.Model):
picture = models.ImageField(upload_to='photos/', blank=True, null=True)
表格:
from django.forms import ModelForm
from random_tasks_app.models import Post
class UploadImageForm(ModelForm):
class Meta():
model = Post
fields = '__all__'
html 文件:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form method = "POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
{%for post in posts%}
<img src="{{ post.picture.url }}"/>
{%endfor%}
</body>
</html>
错误:
raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
ValueError: The 'picture' attribute has no file associated with it.
谢谢。
【问题讨论】:
-
hotel来自哪里? -
当我收到错误时从某个网站复制了这部分代码(以为我可能错过了大括号或其他东西),没有注意到,我将其更改为发布但我仍然得到同样的错误。
-
在 html 文件中将您的代码更改为此,以查看您的 URL 是什么:{%for post in posts%}
{{ post.picture.url }}
{% endfor%} -
@AndreyBorzenko 这会返回一个错误。它只是返回:“图片”属性没有与之关联的文件。
-
@AndreyBorzenko 我得到了它的工作,上传图片时我得到类似'/media/photos/Screenshot_70.png'的东西。试过这个,但它似乎没有工作:
标签: python python-3.x django django-models django-templates