Django AttributeError: 调用 form.is_valid() 总是导致 'is_vaild' 没有这个属性
我花了一整天在找解决办法,几乎把StackOverflow上的所有答案都看了一遍,但还是解决不了我的问题。所以,我只能提出这个问题。
在models.py文件里,我有:
from django.db import models
import datetime
from django.utils import timezone
class Cap(models.Model):
title = models.CharField(max_length=50)
user_id = models.CharField(max_length=100)
dest_id = models.CharField(max_length=100)
cap_id = models.CharField(max_length=500)
text_part = models.FileField(upload_to='texts/%Y/%m/%d')
time_to_live = models.IntegerField()
pub_date = models.DateField()
def __unicode__(self):
return self.title
然后在forms.py文件里,我有:
from django.forms import ModelForm
from latercap.models import Capsule
class CapForm(ModelForm):
class Meta:
model = Cap
fields = '__all__'
接着在views.py文件里,我有:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from myapp.forms import CapForm
def upload(request):
# Handle file upload
if request.method == 'POST':
form = CapForm(request.POST, request.FILES)
if form.is_vaild():
form.save()
# Redirect to the upload page after POST
return HttpResponseRedirect('/myapp/upload/')
else:
form = CapForm() # An empty, unbound form
message = "You can upload your message here!"
context = {'message': message, 'form': form}
# Render upload page with the documents and the form
return render(request, 'myapp/upload.html', context)
最后在upload.html文件里,我有:
<b>{{message}}</b>
<form action="{% url 'myapp:upload' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>Title: {{ form.title }}</p>
<p>From: {{ form.user_id }}</p>
<p>To: {{ form.dest_id }}</p>
<p>No. {{ form.cap_id }}</p>
<p>Open after: {{ form.time_to_live }}</p>
<p>Publish date: {{ form.pub_date }}</p>
<p>My message:</p>
<p>
{{ form.text_part }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
当我在表单里输入正确的值并点击“上传”按钮时,我总是会收到:
> AttributeError at /myapp/upload/ 'CapForm' object has no attribute
> 'is_vaild'
> Request Method: POST Request
> URL: http://127.0.0.1:8000/myapp/upload/
> Django Version: 1.6.5
> Exception Type: AttributeError Exception Value: 'CapForm' object
> has no attribute 'is_vaild'
我尝试过:
- 用
print form.errors
,但什么也没显示 - 在
if
之前用print form.is_valid()
,还是出现错误 - 删除
text_part
,只传request.POST
给form
,依然有错误 - 使用
form(data=request.POST, files=request.FILES)
,还是出错 - 用
print form.is_multipart()
得到的结果是True
- 提交空表单或填写正确的表单都出现同样的错误
我该怎么做才能让这个工作正常呢?非常感谢!
1 个回答
8
is_vaild != is_valid
简单的打字错误