Django表单is_valid总是false

时间:2012-01-02 15:27:50

标签: django django-forms

在我的django应用程序中,即使我添加与管理应用程序中相同的数据,表单也永远不会返回true。我的model.py看起来像:

from django.db import models
from django.db.models import ImageField, signals
from django.dispatch import dispatcher
from django.forms import ModelForm

# Create your models here.
class Image(models.Model):
    emailAddress = models.EmailField(max_length=75)
    image = ImageField(upload_to='photos')
    caption = models.CharField(max_length=100)

class UploadForm(ModelForm):
    class Meta:
        model = Image

我的views.py看起来像:

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from competition.models import Image, UploadForm

# Create your views here.

def index(request):
    images = Image.objects.all().order_by('emailAddress')
    return render_to_response('images/index.html', {'images': images})

def uploadImage(request):
    if request.method == 'POST': # If the form has been submitted...
        form = UploadForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            emailAddress = form.cleaned_data['emailAddress']
            image = form.cleaned_data['image']
            caption = form.cleaned_data['caption']
            i = Image(emailAddress=emailAddress, image = image, caption = caption)
            i.save()
            return HttpResponseRedirect('../image/')
        else:
            return render_to_response('images/upload.html', {'form': form})
    else:
        form = UploadForm() # An unbound form
        return render_to_response('images/upload.html', {'form': form})

我的模板如下:

<html>
<body>
    <form enctype="multipart/form-data" action="/image/uploadImage" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
    </form>
    </body>
</html>

如果我使用管理应用程序但需要通用表单,我可以正常工作,这不起作用,因为它一直要求电子邮件地址或图像(错误出现在图像字段上方)。那么为什么我的表格无效?

3 个答案:

答案 0 :(得分:4)

您需要使用request.FILES以及request.POST实例化您的表单。

另外,您可以保存模型表单,而不是在视图中手动创建图像。

答案 1 :(得分:4)

您有一个必需的图片,但您没有将文件数据绑定到表单。

form = UploadForm(request.POST)

应该是

form = UploadForm(request.POST, request.FILES)

请参阅https://docs.djangoproject.com/en/1.3/ref/forms/api/#binding-uploaded-files

答案 2 :(得分:0)

FileField ImageField 字段有两个地方需要注意:

  1. 在表单元素中需要enctype="multipart/form-data"
<form enctype="multipart/form-data" method="post" action="/foo/">
  1. 需要request.FILES作为表单构造函数。
form = UploadFileForm(request.POST, request.FILES)

请参考:

https://docs.djangoproject.com/en/2.2/topics/http/file-uploads/ https://docs.djangoproject.com/en/2.2/ref/forms/api/#binding-uploaded-files