Django Forms, having multiple “Models” in Meta cla

2019-02-14 00:54发布

问题:

Can we define multiple models in the "Meta class" part of a Form ?

Here is my example:

from django import forms

from django.contrib.auth.models import User , Group

from django.forms import ModelForm

from django.utils.translation import ugettext as _

from profiles.models import Student , Tutor 


class RegistrationForm(ModelForm):
    email           = forms.EmailField(label=_('Email Address:'))
    password        = form.CharField(label=_('Passsword:') , widget = forms.PasswordInput(render_value = False))
    password1       = form.CharField(label=_('Verify Passsword:') , widget = forms.PasswordInput(render_value = False))

    class Meta:
        model = [Student , Tutor] ## IS THIS TRUE ???

回答1:

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.



回答2:

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.



回答3:

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>