开发者

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜