我正在尝试为我的一个班级制作一个搜索表单。表格的模型是:
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'
我不确定发生了什么事,有人可以帮助我吗?谢谢!
答案 0 :(得分:145)
出于某种原因,您在检查is_valid()
后重新实例化表单。表单仅在调用cleaned_data
时获得is_valid()
属性,并且您尚未在此新的第二个实例上调用它。
摆脱第二个form = SearchForm(request.POST)
,一切都应该好。
答案 1 :(得分:6)
我会写这样的代码:
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))
非常像documentation。
答案 2 :(得分:2)
有时,如果我们忘记了
return self.cleaned_data
在django表单的清除功能中,虽然form.is_valid()
将返回True
,但我们不会有任何数据。