以 Django 形式上传图像

问题描述 投票:0回答:2

我正在尝试从表单上传图像,但每当我提交时,除图像字段之外的所有内容都会保存在数据库中。但是当我尝试从管理面板执行相同操作时,它会起作用。
模型.py

class Post(models.Model):
    title = models.CharField(("Title"), max_length=100)
    title_image = models.ImageField(
        ("Title Image"), 
        upload_to='static/Images/TitleImages/',
         max_length=None,
         blank = True,null = True)

Forms.py

class AddPostForm(ModelForm):
    class Meta:
        model = Post
        fields = ['title','title_image']

Views.py

class AddPostView(LoginRequiredMixin,CreateView):
    model = Post
    template_name = 'MainSite/add_post.html'
    fields = '__all__'

    def dispatch(self, request, *args, **kwargs):
        if request.user.is_anonymous:
            messages.error(request,"You need to login to access this page")
            return redirect('/')
        elif request.user.is_superuser:
            if request.method == "POST":
                form = AddPostForm(request.POST)
                if form.is_valid():
                    form.save()
                    messages.success(request,"POST added successfully")
                    return redirect('/')
                else:
                    print("error")
            else:
                print("method is not post")
            form = AddPostForm()        
            return render(request,'MainSite/add_post.html',{'form':form})
        else :
            messages.error(request,"You need to have superuser permission to access this page")
            return redirect('/')

addpost.html

<form action= "" method="POST" enctype="multipart/form-data"> 
    {% csrf_token %}

                      {{ form.media }}
                            {{ form|crispy}}
                    
                  <button class="btn btn-primary profile-button" style = "width:150px;"type="submit" >Add Post</button></div>

  </form>

我的模型有两件事标题和标题图像,但每当我提交时,仅保存标题,并且当我通过管理面板进行操作时,它可以工作。 我不知道我在这里做错了什么任何建议都会有帮助。
预先感谢

django django-forms
2个回答
1
投票

您必须通过

request.FILES
才能保存文件

if request.method == "POST":
   form = AddPostForm(request.POST, request.FILES)
   if form.is_valid():
      form.save()
      messages.success(request,"POST added successfully")
      return redirect('/')

0
投票

处理文件时,请确保 HTML 表单标签包含 enctype=”multipart/form-data” 属性。

示例:

这样你就可以通过 Django Forms 提交图像。
© www.soinside.com 2019 - 2024. All rights reserved.