Django AttributeError:调用form.is_valid()总是导致Object没有属性' is_vaild'

时间:2014-06-02 14:40:56

标签: python django forms django-forms

我一直在寻找解决方案一整天,我几乎已经完成了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>

当我在表单中设置正确的值并点击&#34;上传&#34;按钮,我总是得到:

> 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结果
  • 提交一个空的或填写正确的表单都会出现同样的错误

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

1 个答案:

答案 0 :(得分:7)

is_vaild != is_valid

简单错字