“Django:模型表单”对象没有属性'cleared_data'“
我正在为我的一个课程做一个search表单。 表格的模型是:
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'
我不确定发生了什么事,有人可以帮我吗? 谢谢!
出于某种原因,您在检查is_valid()
后重新实例化表单。 当is_valid()
被调用时,Forms只会获得一个is_valid()
属性,并且你没有在这个新的第二个实例上调用它。
只要摆脱第二种form = SearchForm(request.POST)
,一切都应该是好的。
我会写这样的代码:
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))
非常像文档 。
有时候,如果我们忘记了
return self.cleaned_data
在django表单的clean函数中,虽然form.is_valid()
将返回True
但是我们不会有任何数据。