modelForm在文件上传时给出验证错误

时间:2013-05-22 09:47:22

标签: django django-forms django-file-upload

我正在尝试上传裸机文件,但在验证模型表单时似乎存在问题。

这是我的模特:

class quiz(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=200)
    questions_file = models.FileField(upload_to=get_path)
    end_date = models.DateField()
    time = models.IntegerField()


    def __unicode__(self):
        return self.name

我的forms.py

class quizForm(ModelForm):
class Meta:
    model = quiz
    fields = ['title','questions_file','end_date','time']

相关观点:

def upload(request):
    if request.user.is_authenticated():     
        if request.method == 'POST':
                form = quizForm(request.POST,request.FILES)
                if form.is_valid():
                    quiz = form.save(commit=False)
                    quiz.user = request.user
                    quiz.save()
                else:
                    return HttpResponse(form.errors)
        else:
            form = quizForm()
            return render_to_response('upload.html',{'form':form},context_instance=RequestContext(request))
    else:
        return HttpResponse('Not logged in')

模板:

<form enctype="multi-part/form-data" action='/test-upload/' method='POST'>
{% csrf_token %}
{{form.as_p}}
<input type='submit' name='submit'>
</form>

通过表单提交文件。我收到了questions_file的http响应,即文件未正确验证。

提前致谢。另外请忽略缩进错误,我是SO格式的菜鸟。

1 个答案:

答案 0 :(得分:0)

表格编码类型中的错误:

<form enctype="multipart/form-data" action='/test-upload/' method='POST'>
    {% csrf_token %}
    {{form.as_p}}
    <input type='submit' name='submit'>
</form>