Reputation: 1105
I am trying to make a form object in Django views and run the is_valid() method on it. I have tried
1.
form = LandingPageForm(initial={'user':user, 'name':"Shahrukh"})
and
2.
form = LandingPageForm(data={'user':user, 'name':"Shahrukh"})
but running form.is_valid() method returns false both the times,
I also tried
3.
form = LandingPageForm({'user':user, 'name':"Shahrukh"})
but is_valid() returned false, even though there were no errors.
In case 2 and 3 gave errors on the user field "Select a valid choice. That choice is not one of the available choices."
which I am assuming is because user is a foreign key field and is rendered as a drop-down select field in the form.
What is the correct way of doing it?
I want to know how can we create a form object in Django views and run is_valid() on it
Upvotes: 1
Views: 62
Reputation: 1105
I resolved my issue. The error Select a valid choice. That choice is not one of the available choices.
was coming because it was expecting the id of the user and not the user object while creating the form.
As far as I discovered, here are my observations -
instance={'data':value}
doesn't create the form object and fill data in it, hence is_valid
always gave false and form.errors
was also empty.
using the data
parameter actually creates the form object.
Model forms of Models containing the foreign key field should be instantiated with the id of the object and not the object itself.
Upvotes: 1