【问题标题】:Django ImageField has no url attribure associated with itDjango ImageField 没有与之关联的 url 属性
【发布时间】: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


【解决方案1】:

您可以添加一个 default 属性,它将被解决

picture = models.ImageField(upload_to='default/', blank=True, null=True, default='default.jpg' )

【讨论】:

  • 对我不起作用,但我注意到一件奇怪的事情,由于某种原因,HTML 没有显示任何图像,即使它与 django 无关。我认为这与路由有关。
  • 似乎 django 阻止了正在显示的任何图像形式,即使我试图显示不使用 django 功能的图像 ``` ``` 如果我使用普通 html 打开它,但在运行它时有效django 服务器它只是不工作
  • 也许,我认为如果你提交 ImageField 空 django 会引发错误
  • 解决了,谢谢。忘记在 urls.py url 模式的末尾添加:+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-28
  • 2016-02-06
  • 2022-12-11
  • 2015-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多