Django:模型表格“对象没有属性'cleaned_data'”


83

我正在尝试为我的一门课做搜索表格。表单的模型为:

from django import forms
from django.forms import CharField, ModelMultipleChoiceField, ModelChoiceField
from books.models import Book, Author, Category

class SearchForm(forms.ModelForm):
    authors = ModelMultipleChoiceField(queryset=Author.objects.all(),required=False)    
    category = ModelChoiceField (queryset=Category.objects.all(),required=False)
    class Meta:
        model = Book
        fields = ["title"]

我正在使用的视图是:

from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template import RequestContext
from books.models import Book,Author
from books.forms import BookForm, SearchForm
from users.models import User

def search_book(request):
    if request.method == "POST":
        form = SearchForm(request.POST)
        if form.is_valid():
            form = SearchForm(request.POST)
            stitle = form.cleaned_data['title']
            sauthor = form.cleaned_data['author']
            scategory = form.cleaned_data['category']
    else:
        form = SearchForm()
    return render_to_response("books/create.html", {
        "form": form,
    }, context_instance=RequestContext(request))

表单显示正常,但是提交时出现错误: 'SearchForm' object has no attribute 'cleaned_data'

我不确定发生了什么,有人可以帮我吗?谢谢!


8
为什么要打form = SearchForm(request.POST)两次电话?
hughdbrown

@SafwanSamsudeen我的评论与10年前被接受的正确答案相同。问题实际上是该代码不应再次调用SearchForm。
休格布朗

Answers:


178

由于某种原因,您在检查后重新实例化了表格is_valid()。表单仅cleaned_datais_valid()被调用时获得属性,而您尚未在此新的第二个实例上调用它。

只是摆脱第二form = SearchForm(request.POST),一切都应该很好。


7

我会这样写代码:

def search_book(request):
    form = SearchForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        stitle = form.cleaned_data['title']
        sauthor = form.cleaned_data['author']
        scategory = form.cleaned_data['category']
        return HttpResponseRedirect('/thanks/')
    return render_to_response("books/create.html", {
        "form": form,
    }, context_instance=RequestContext(request))

非常像文档


好吧,那行得通!表格的定义位置是否有很大的不同?
约瑟夫

我不知道您的问题是什么,但是我认为SearchForm(request.POST)没有必要打两次电话。其余的只是修饰窗口:我碰巧喜欢这种折叠Form构造参数的方式,因此您只需要一个调用。
hughdbrown

还是@Daniel Roseman所说的。如果我是您,我会选择他作为首选答案,因为他会找出确切原因。
hughdbrown

2

有时,如果我们忘记了

return self.cleaned_data 

在django表单的clean函数中,尽管form.is_valid()will返回,但我们将没有任何数据True

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.