Search code examples
djangoformsets

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.


Solution

  • 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" />