[Fixed]-Django Forms, having multiple "Models" in Meta class?

11👍

No. But you don’t need to. Instead of instantiating and validating a single form, do it for each type of form you need to support.

# Define your model forms like you normally would
class StudentForm(ModelForm):
    ...

class TutorForm(ModelForm):
    ...

class RegistrationForm(Form):
    email = ...
    ...

# Your (simplified) view:
...
context = {
    'student_form': StudentForm(),
    'tutor_form': TutorForm(),
    'registration_form': RegistrationForm()
}
return render(request, 'app/registration.html', context)

# Your template
...
<form action="." method="post">
    {{ student_form }}
    {{ tutor_form }}
    {{ registration_form }}
    <input type="submit" value="Register">
</form>

If this means field names are duplicated across forms, use form prefixes to sort that out.

👤roam

6👍

No, it is not possible to define multiple models in the Meta class.

You can create a model form for each model, and then put multiple forms in the same html <form> tag using the prefix argument.

Then in your view, you can check that each model forms is valid before saving.

Note that the django contrib.auth app comes with a UserCreationForm (view source). You can probably re-use that instead of writing your own form.

0👍

define your models in your form.py

form1 #using 1st model

form2 #using 2nd model

now edit your views.py in get method

args = {

"form1" = form1(),

"form2" = form2()

}

return render(request, "template_name", args)

now edit your template

<form .....>

form1.as_p

form2.as_p

...

</form>

Leave a comment