239👍
For some reason, you’re re-instantiating the form after you check is_valid()
. Forms only get a cleaned_data
attribute when is_valid()
has been called, and you haven’t called it on this new, second instance.
Just get rid of the second form = SearchForm(request.POST)
and all should be well.
12👍
I would write the code like this:
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))
Pretty much like the documentation.
- [Django]-Copy a database column into another in Django
- [Django]-Django: Error: You don't have permission to access that port
- [Django]-Get model's fields in Django
3👍
I was facing the same problem,
I changed the code like this
if request.method == "POST":
form = forms.RegisterForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
fname = form.cleaned_data.get('fname')
lname = form.cleaned_data.get('lname')
email = form.cleaned_data.get('email')
pass1 = form.cleaned_data.get('pass1')
pass2 = form.cleaned_data.get('pass2')
- [Django]-Cancel an already executing task with Celery?
- [Django]-Django URLs TypeError: view must be a callable or a list/tuple in the case of include()
- [Django]-Django: Why do some model fields clash with each other?
2👍
At times, if we forget the
return self.cleaned_data
in the clean function of django forms, we will not have any data though the form.is_valid()
will return True
.
- [Django]-Use Python standard logging in Celery
- [Django]-How do I filter ForeignKey choices in a Django ModelForm?
- [Django]-Django: How to manage development and production settings?
0👍
Another way the error
'MyForm' object has no attribute 'cleaned_data'
may show up is if you try to update an existing model instance without passing request.POST
to the relevant subclass of ModelForm
. For example, we get this error in the following case:
a = Article.objects.get(id=1)
f = ArticleForm(instance=a)
f.save() # <--- 'MyForm' object has no attribute 'cleaned_data'
Changing it to the following
a = Article.objects.get(id=1)
f = ArticleForm(request.POST, instance=a)
# ^^^^^^^^^^^^ <--- must be passed
f.save()
resolves the error.
- [Django]-How to produce a 303 Http Response in Django?
- [Django]-Find object in list that has attribute equal to some value (that meets any condition)
- [Django]-In django do models have a default timestamp field?