【问题标题】:The 'header_image' attribute has no file associated with it“header_image”属性没有与之关联的文件
【发布时间】:2021-06-05 10:27:53
【问题描述】:

当我用图片创建新帖子时,一切都很好,但如果我编辑它,我想使用“清除”按钮删除图片,然后出现此错误,如果我更改,则没有任何变化,但没有错误

这里是 models.py `

from django.db import models
from django.urls import reverse


class Post(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(
        'auth.User',
        on_delete=models.CASCADE,
    )
    body = models.TextField()
    header_image =  models.ImageField(blank=True, null=True, upload_to="images/", default='#') #new

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post_detail', args=[str(self.id)])`

这里是 views.py `

from django.shortcuts import render
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy

from .models import Post


class BlogListView(ListView):
    model = Post
    template_name = 'home.html'

class BlogDetailView(DetailView):
    model = Post
    template_name = 'post_detail.html'

class BlogCreateView(CreateView):
    model = Post
    template_name = 'post_new.html'
    fields = ['title', 'author', 'body', 'header_image']

class BlogUpdateView(UpdateView):
    model = Post
    template_name = 'post_edit.html'
    fields = ['title', 'body', 'header_image']

class BlogDeleteView(DeleteView):
    model = Post
    template_name = 'post_delete.html'
    success_url = reverse_lazy('home')

@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`

post_base.html

`{% load static %}
<html>
  <head>
    <title>Django blog</title>
    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400"
    rel="stylesheet">
    <link href="{% static 'css/base.css' %}" rel="stylesheet">
  </head>
  <body>
    <div>
      <header>
        <div class="nav-left">
          <h1><a href="{% url 'home' %}">Django blog</a></h1>
            <h2><a href="http://127.0.0.1:8001/admin/">Admin</a></h2>

        </div>
        <div class="nav-right">
           <a href="{% url 'post_new' %}">+ New Blog Post</a>
        </div>
      </header>
      {% if user.is_authenticated %}
        <p>Hi {{ user.username }}!</p>
      {% else %}
        <p>You are not logged in.</p>
        <a href="{% url 'login' %}">Log In</a><br>
          <p><a href="http://127.0.0.1:8001/accounts/signup/">Sign up</a></p>
      {% endif %}
    {% block content %}
    {% endblock content %}
    </div>
  </body>
</html>`

post_detail.html `

{% extends 'base.html' %}

{% block content %}
    <div class="post-entry">
        <h2>{{ post.title }}</h2>
        <p>{{ post.body }}</p>
    </div>

    <p><a href="{% url 'post_edit' post.pk %}">+ Edit Blog Post</a></p>
    <p><a href="{% url 'post_delete' post.pk %}">+ Delete Blog Post</a></p>
    <img src="{{ post.header_image.url|default_if_none:'#' }}">

    {{ post.body|safe }}
{% endblock content %}`

post_new.html `

{% extends 'base.html' %}

{% block content %}
    <h1>New post</h1>
    <form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
      {{ form.as_p }}
      <input type="submit" value="Save" />
    </form>
{% endblock content %}`

post_edit.html `

{% extends 'base.html' %}

{% block content %}
    <h1>Edit post</h1>
    <form action="" method="post">{% csrf_token %}
        {{ form.as_p }}
    <input type="submit" value="Update" />
    </form>

{% endblock content %}`

【问题讨论】:

  • 您可以尝试为图像字段添加适当的默认值吗?
  • 如果我理解正确,那么您的意思是:我将 models.py 和 views.py 中的“#”更改为“fox.jpeg”,这是我在桌面上的,但它没有帮助

标签: python django django-models django-views


【解决方案1】:

enctype='multipart/form-data' 表示不会对字符进行编码。这就是为什么在将文件上传到服务器时使用这种类型的原因。因此当表单需要上传二进制数据(如文件内容)时,使用 multipart/form-data。

您忘记在post_edit.html form 中添加enctype='multipart/form-data',这就是您的文件没有发送到Django 的原因。以下代码应该可以工作。

post_edit.html

{% extends 'base.html' %}

{% block content %}
    <h1>Edit post</h1>
    <form action="" method="post" enctype='multipart/form-data'>
        {% csrf_token %}
        {{ form.as_p }}
    <input type="submit" value="Update" />
    </form>

{% endblock content %}

【讨论】:

    猜你喜欢
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 2023-02-21
    • 2021-11-18
    • 2021-02-11
    • 2020-03-08
    相关资源
    最近更新 更多