hakubaa
hakubaa

Reputation: 169

Python/Django - Generating forms for models.

I have two questions concerning models and forms.

1) What is the best way to create automatically forms for the models?

In the example below I have two models - ModelA and ModelB. I need forms for them - ModelAForm and ModelBForm. They should be defined automatically. I do not want to do it manually, because in the future I will add other models, and all the forms will look the same. I am thinking about creating special decorator for models and use modelform_factory.

from django.db import models
from django.forms import ModelForm

class ModelA(models.Model):
    ...

class ModelB(models.Model):
    ...

class ModelAForm(ModelForm):
    class Meta:
       abstract = ModelA

class ModelBForm(ModelForm):
    class Meta:
        abstract = ModelB

2) Assuming I am using only ModelForm forms, it is possible to find the form for the model? Example. I have two models ModelA and ModelB, and two forms ModelAForm and ModelBForm. I have instance of ModelA and I would like to identify proper form for this model which I will pass to template - in this case ModelAForm.

Upvotes: 1

Views: 1330

Answers (2)

trixn
trixn

Reputation: 16354

Django provides some generic editing views. You only have to provide a model and the view will generate the form automatically. If you want to use the forms to create or update instances you can just use them.

If your really need to create the forms yourself you can use the modelform_factory that these views use themself to create the correct form for your model. But i would first go with the generic views as long as they can be modified to suit your needs.

Just pass it your model and optionally the fields you want. If you omit the fields, all fields will be generated:

from .models import MyModel
from django.forms.models import modelform_factory

my_form = modelform_factory(MyModel, fields=['name', 'age', 'job'])

Upvotes: 4

LinPy fan
LinPy fan

Reputation: 310

There's ModelForm in django. Here's fragment of documentation and link for it. https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/

class ArticleForm(ModelForm):
    class Meta:
        model = Article
        fields = ['pub_date', 'headline', 'content', 'reporter']

You're probably looking for generic class-based views, where you only pass form_class and model instances, everything else django handles without your help. Link for them - https://docs.djangoproject.com/en/1.10/ref/class-based-views/

Upvotes: 1

Related Questions