首页 > 解决方案 > 我无法在 django 的新博客文章中添加图片

问题描述

请帮助我,我正在使用基于类的视图,现在我将使用 Createview 创建新帖子我添加了所有字段,包括代表缩略图的图像,所以如果我去http://127.0.0.1:8000/pages/blog /new/我得到一个表格,如果我填写字段并提交,我会返回到表格,说图像字段是必需的,同时我已经插入了一个图像,这是图片中的错误 ,这是我下面的代码

视图.py

class BlogCreateView(LoginRequiredMixin, CreateView):
    model = Blog
    fields = ['title', 'categories', 'overview', 'thumbnail', 'summary']

blog_form.html

<div class="content-section text-center">
     <form method="POST">
         {% csrf_token %}
         <fieldset class="form-group ">
             <legend class="border-bottom mb-4 h2">Blog Post</legend>
             {{ form|crispy }}
         </fieldset>
         <div class="form-group">
             <button class="btn btn-outline-info" type="submit">Post</button>

         </div>
     </form>
</div>

标签: django-formsdjango-templates

解决方案


您需要在表单中添加“enctype="multipart/form-data",因此:

<form method="post" enctype="multipart/form-data">

请参阅详细说明是这个详尽的答案: What does enctype='multipart/form-data' mean?


推荐阅读