frustrated_dude
frustrated_dude

Reputation: 23

Using two models for a form in Django

I've run into a problem with using two models for my form in Django. I have two models, Animal and Family, both with a "name" field.

I use the two modelforms on my template for my form, and when it's submitted, the POST data for 'name' only returns one value.

Short of renaming the 'name' field in my models, is there any way around this?

Thanks for your help. This is my first post here.

Upvotes: 2

Views: 218

Answers (2)

user257858
user257858

Reputation:

You could make use of the prefix-argument when initializing the modelforms;

animal_form = AnimalForm(request.POST or None, prefix="animal")
family_form = FamilyForm(request.POST or None, prefix="family")

Which will output something like;

<input id="id_animal-name" type="text" />
<input id="id_family-name" type="text" />

Upvotes: 3

stefanw
stefanw

Reputation: 10570

You can get the different POST values that are under the same name with request.POST.getlist.

However, the correct value will then depend on the position of the input field in the form (I guess) and this really can't be a good idea. Change the name of the field, not in the model, but in your form class (I hope you use one).

Upvotes: 0

Related Questions