views:

99

answers:

1

I want to have a ModelForm that can create_or_update a model instance based on the request parameters.

I've been trying to cobble something together, but am realizing that my python fu is not strong enough, and the ModelForm implementation code is a quite hairy.

I found this update_or_create snipplet for working with a Model, but I think it would be incredibly useful if it were integrated with a ModelForm.

I would expect it to behave similarly to ModelForm.save():

class BetterModelForm(forms.ModelForm):
    def create_or_update(self):
        #magic
        return (instance, created, updated)

Conversely I'd also be interested in hearing compelling reasons why this is not a good idea.

+1  A: 

This isn't really something that belongs in the ModelForm itself. Models already do this automatically - if the model instance has a value for pk, it is updated, otherwise it is inserted. So all you need to do when you instantiate your form is to pass in either an existing model instance, which will be updated on form save, or an empty instance (or even just None), in which case a new instance will be created.

Daniel Roseman