(帮助)Django模型表单无法识别图像文件

时间:2017-10-09 00:27:51

标签: python django forms

我使用我的一个模型创建了一个表单,即(Post),用于我的博客网站。该表格适用于作者发表文章。在该表单中,有一个Image属性,编写者可以在其中上传图像。但是,当我尝试上传图像并发布它时,我得到一个反馈说“需要字段”,我认为表单没有识别图像我试图上传到数据库。请帮忙:

这是来自views.py的表单视图:

def formview(request):
    form = PostForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
    return render(request, 'form.html', {'form':form})

这是来自forms.py:

from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    image = forms.FileField
    class Meta:
        model = Post
        fields = ['category', 'title', 'body', 'image', 'author']

来自我的models.py:

class Post(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=100)
pub_date = models.DateTimeField(auto_now_add=True)
body = models.TextField()
image = models.FileField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
likes = models.IntegerField(default=1)

def __str__(self):
    return self.title

这是我的forms.html模板:

<form method="POST" action="">
{% csrf_token %}

{{ form.as_p }}

<button type="submit">Post</button>

这是我的urls.py:

from django.conf.urls import url
from . import views

app_name = 'posts'

urlpatterns = [
    url(r'^$', views.homeview, name='homeview'),
    url(r'^(?P<pk>[0-9]+)$', views.postview, name='postview'),
    url(r'^category/(?P<pk>[a-zA-Z0-9]+)/$', views.categoryview, 
name='categoryview'),
    url(r'^author/(?P<pk>[a-zA-Z0-9]+)/$', views.authorview, name='authorview'),
    url(r'^add_post/$', views.formview, name='formview'),

]

这些图片可能有助于解释我想说的内容:

Filling the form and selecting the picture

Error message after trying to post

谢谢

1 个答案:

答案 0 :(得分:0)

def formview(request):
    if request.method == 'POST':
        form = PostForm(request.POST,request.FILES)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.save()
    else:
        form = PostForm()
    return render(request, 'form.html', {'form':form})

form = PostForm(request.POST,request.FILES),您需要将FILES添加到PostForm