Create models.forms dynamically in Django

3

Good Night with everyone

There is some way to create Django form from the existing Django models in a dynamic, automatic way or maybe by doing a for or a loop.

I ask this question already if I have for example 2 Company and Book models, then I would have to create the forms in the forms.py file by doing the following:

class CompanyForm(forms.ModelForm):
  class Meta:
      model = Company

class BookForm(forms.ModelForm):
  class Meta:
      model = Book

As you can tell, it is repetitive and if instead of 2 models I have 100 models, that would be a very repetitive job.

I hope someone can help me.

Thank you very much

    
asked by Barckl3y 21.02.2018 в 04:58
source

1 answer

3

There are several topics here, first, with respect to your specific doubt, I will show you a way, but not before clarifying that it is not recommended ... do you know django contentype? Documentation django contenttype , well, that's where the django data is stored, so one of the possible solutions would be this:

from django.contrib.contenttypes.models import ContentType  
from django import forms  

def get_object_form( id_tipo,  excludes=None ):  
    tipo = ContentType.objects.get( pk=id_tipo ) 
    modelo = tipo.model_class( ) 
    class _ObjectForm( forms.ModelForm ):
        class Meta:
            model = modelo
            fields = '__all__'
    return _ObjectForm

Basically, a queryset is made to contentype with the pk of the model in question. It is not viable of course, to iterate all the models and create a form for each one but more as a reusable function that allows to receive any, in the views it is only that you call it assigned to a variable and then you can use all the normal methods of django forms as save ().

Now, why is not recommended: As you know, the idea of the forms for each model is that you can play with the fields by creating certain validation rules or modifying their structure as you consider, not all the models have the same fields or the same data patterns .... if the argument is that there may be 100 models in your application, I think that the subject is to review the design of the data model itself, because maybe it is not correct, it is too heavy and possibly requires modularity.

I hope it has been useful and has been clear to you.

    
answered by 21.02.2018 / 19:20
source