gpt4 book ai didi

python - Django:模型表单 "object has no attribute ' clean_data'"

转载 作者:IT老高 更新时间:2023-10-28 21:37:28 24 4
gpt4 key购买 nike

我正在尝试为我的一门类(class)制作搜索表单。表格的型号是:

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"]

我正在使用的 View 是:

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() 时才获得 cleaned_data 属性,而您还没有在这个新的第二个实例上调用它。

只要去掉第二个 form = SearchForm(request.POST) 就可以了。

关于python - Django:模型表单 "object has no attribute ' clean_data'",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4308527/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com