Django AttributeError:调用 form.is_valid() 总是导致 Object 没有属性'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,但未显示任何内容
  • print form.is_valid()if之前,仍然给出错误
  • 删除text_part,只将request.POST传递给form,仍然会出现错误
  • 使用form(data=request.POST, files=request.FILES),仍然存在错误
  • print form.is_multipart()给我一个True的结果
  • 提交一个空的或正确填写的表格都会出现相同的错误

我该怎么做才能完成这项工作?非常感谢!

is_vaild != is_valid

简单的打字错误

相关内容

  • 没有找到相关文章

最新更新