Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 825
killerbarney Avatar asked Oct 13 '22 18:10

killerbarney


1 Answers

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.

like image 64
Daniel Roseman Avatar answered Oct 27 '22 08:10

Daniel Roseman