I recently had a use case where I needed to have a single form that could act as either a create or update form. The tricky part was that I wouldn’t know which one was necessary until the data was submitted by the user.
To solve this, I started with Django’s generic UpdateView and overwrote the get_object method so that it would either get the existing record or create a new one (using get_or_create) based on the data being submitted. In my case (and the example below), I had two values that determined whether a new record was necessary or if an existing one should be used.
The underlying ModelForm didn’t require any modification (you could even just use Django’s automatically generated ModelForm by specifying the model in your view).
Here’s the code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.views.generic import UpdateView | |
from forms import MyModelForm | |
from models import MyModel | |
class MyUpdateView(UpdateView): | |
# specify a custom ModelForm | |
form_class = MyModelForm | |
# or simply specify the Model | |
# model = MyModel | |
def get_object(self, queryset=None): | |
# get the existing object or created a new one | |
obj, created = MyModel.objects.get_or_create(col_1=self.kwargs['value_1'], col_2=self.kwargs['value_2']) | |
return obj | |
Nice! exactly what I was looking for. Thanks!
Muito bom me ajudou bastante !!!!!!!!
Just what I was looking for. Thanks friend!
Perfect! Thank you so much. This is exactly what I was looking for. However, when I click on the link related to this view the object is already created, so if I decide to go back I can’t undo it. However, I don’t mind the way it works now. Thanks man.
Woow this is great! I was going to change updateview to function base view, thank you!
There is one problem with this if you are on that view and you refresh the page an empty form will be submitted, however it wont afttect much since if a person fills again that info, it will be updated BUT I DONT WANT TO SIBMIT THAT EMPTY FORM TOO.
this is working like a charm maann… thank you…. saved my night