Equivalent to get_model for ModelForms?

I have several ModelForm classes, each of which represents a different model. I would like to have a generic create function that loads the specified model form based on the URL parameter. Dynamic dynamic loading of the model can be obtained as follows:

model_name = 'TestModel'
m = get_model('AppLabel', model_name)

Does anyone know how I can achieve the same for ModelForms, something like:

modelform_name = 'TestModelForm'
f = get_form('AppLabel', modelform_name)
if f.is_valid():
    ...

I can’t think of a way to do this using common views - they need to pass a ModelForm, not just its name. If I get a model with get_model, then I pass it to the general view, it will display the form, but I can not exclude the model fields.

TIA for any advice

+3
source share
2 answers

ModelForm, . ( ).

, :

  • ModelForm : getattr .

  • ModelForm , (< 30) : , ModelForm. :

    from some_app.forms import FirstModelForm
    from another_app.forms import SecondModelForm
    from additional_app.forms import FirstModelForm as AdditionalAppFirstModelForm # Will allow for managing conflicting names easily.
    
    form_mapping = {
        'FirstModelForm': FirstModelForm,
        'SecondModelForm': SecondForm,
        'AdditionalAppFirstModelForm': AdditionalAppFirstModelForm,
    }
    
    request_form_class = request.POST.get('form_class')
    f = form_mapping.get(request_form_class)(request.POST)
    
    if f.is_valid():
        f.save()
    
  • . ModelForm BaseModelFormMetaclass . , , ModelForm Model "", . , .

( , , ), β„– 2.

+2

forms.py forms. __init__.py ModelForm s.

sdolan Option # 1.

-1

Source: https://habr.com/ru/post/1755077/


All Articles