baldr
baldr

Reputation: 2999

Django: one ModelForm for subclasses

I have an abstract model like this:

class BaseAgent(models.Model):
    name = models.CharField('Name', max_length=128, null=False, default='')

    class Meta:
        abstract = True

I am creating subclasses of this model with exact agent types. For example Agent001, Agent002, whatever.

I would like to have only one class of ModelForm form for each of these subclasses. I am going to pass it to the UpdateView view. But it requires to have Meta.model being specified.

class AgentEditForm(ImprovedForm, forms.ModelForm):

    class Meta:
        model = BaseAgent  # here I would like to have Agent001, Agent002 or others
        exclude = ()

I have a subclass of ModelForm with some mixin added and would like to use this class (lets call it ImprovedForm).

Ideally I would like to have one string in urls.py to call a view with only model name passed (and form too).

url(r'^agent001/new$', login_required(views.AgentCreateUpdateView.as_view(model=Agent001, form=ImprovedAgentForm)), name='new_agent001'),

Of course I can create a form for each model like this:

class Agent001EditForm(AgentEditForm):

    class Meta:
        model = Agent001

But it is just a copy-pasting. Imagine that I have more than two classes and will have more in the future. I'd like to have a generic solution.

How can I do it with minimal lines of code?

Upvotes: 2

Views: 374

Answers (1)

Alex Polekha
Alex Polekha

Reputation: 1690

forms.py

import sys

for model in (Agent001, Agent002):
    form_name = model.__name__ + 'EditForm'

    class AgentEditForm(forms.ModelForm):
        class Meta:
            model = model
            exclude = ()

    AgentEditForm.__name__ = form_name
    setattr(sys.modules[__name__], form_name , AgentEditForm)
    del AgentEditForm

Upvotes: 1

Related Questions