【问题标题】:ValueError at /accounts/profile/ The 'image' attribute has no file associated with it/accounts/profile/ 处的 ValueError 'image' 属性没有与之关联的文件
【发布时间】:2019-05-27 18:31:38
【问题描述】:

当用户不是超级用户或没有个人资料图片(通过管理员中的 userprofile 提交)时,会发生此错误。

/accounts/profile/ 处的 ValueError 'image' 属性没有与之关联的文件。 请求方法:GET 请求网址:http://127.0.0.1:8000/accounts/profile/

模板渲染时出错

In template /Users/joseph/Documents/django/tutorial/accounts/templates/base.html, error at line 17
The 'image' attribute has no file associated with it.
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

9     <meta charset="utf-8">
10    <html lang="en" dir="ltr">
11  
12  <!-- Navigation bar -->
13  
14    <br>
15    <nav class="navbar navbar-expand-lg navbar-green bg-light">
16    <a class="navbar-brand" href="/accounts/home">MySite</a>
17    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
18      <span class="navbar-toggler-icon"></span>
19    </button>
20        {% if user.is_authenticated %}
21    <div class="collapse navbar-collapse" id="navbarNav">
22      <ul class="nav navbar-nav ml-auto">
23        <li class="nav-item">
24          <a class="nav-link"   href="/accounts/explore/">Explore</a>
25        </li>
26        </ul>
27      <ul class="nav navbar-nav ml-auto">

models.py:

class UserProfile(models.Model):
   user = models.OneToOneField(User, models.CASCADE)
   description = models.CharField(max_length=100, blank=True, default='')
   city = models.CharField(max_length=100, blank=True, default='')
   website = models.URLField(blank=True, default='')
   contactNumber = models.IntegerField(blank=True, default=0)
   image = models.ImageField(upload_to='profile_image', blank=True)

def __str__(self):
    return self.user.username

为什么会这样?它实际上不能是base.html(扩展)?如果还有什么需要添加来帮助解决问题的,请告诉我。谢谢

【问题讨论】:

    标签: python django


    【解决方案1】:

    查找您正在渲染图像的行(在您的模板文件中,例如base.html)并添加一个 if 条件。比如:

    {% if item.image %}
      <img target="_blank" src="{{ item.image.url }}" />
    {% endif %}
    

    我认为这是不言自明的,但如果需要,请随时提出任何问题。

    【讨论】:

      【解决方案2】:

      您可以将“null=True”添加到 ImageField()。 另外,请检查图像是否已在管理员中成功上传。如果有,请尝试重新上传图片并重试。

      【讨论】:

        猜你喜欢
        • 2019-02-19
        • 2023-02-21
        • 2016-02-06
        • 2020-01-16
        • 2021-02-11
        • 2020-03-08
        • 2020-08-11
        • 1970-01-01
        • 2022-12-11
        相关资源
        最近更新 更多