killerbarney
killerbarney

Reputation: 943

Django design patterns - Forms for Create and Update a Model

Suppose I want to create and update a model. What fields are displayed and the type of validation depends on the action (create or update). But they still share a lot of the same validation and functality. Is there a clean way to have a ModelForm handle this (besides just if instance exists everywhere) or should I just create two different model forms?

Upvotes: 5

Views: 880

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599630

Two possibilities spring to mind. You could set an attribute in the form's __init__ method, either based on a parameter you explicitly pass in, or based on whether self.instance exists and has a non-None pk:

class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        # either:
        self.edit = kwargs.pop('edit', False)
        # or:
        self.edit = hasattr(self, instance) and self.instance.pk is not None
        super(MyModelForm, self).__init__(*args, **kwargs)
        # now modify self.fields dependent on the value of self.edit

The other option is to subclass your modelform - keep the joint functionality in the base class, then the specific create or update functionality in the subclasses.

Upvotes: 4

Related Questions