I want to show the form present in CreateView
if there was no item exists inside a model. Else I need to show the form exists in the UpdateView
. So that it would load the already saved values. Later I should save the data to db by calling update_or_create
method.
Is this possible?
Instead of messing with a double purpose view, which is not trivial to find out which and when to run the correct method (and not recommended), add a third view that will redirect to CreateView or EditView.
It should look something like this:
from django.core.urlresolvers import reverse
class AddItemView(generic.CreateView):
...
class EditItemView(generic.EditView):
...
class UpdateItemRedirectView(generic.RedirectView):
def get_redirect_url(self):
if Item.objects.get( ...criteria... ).exists():
return reverse("url_name_of_edit_view")
else:
return reverse("url_name_of_add_view")
The other "double purpose" view solution that @AviahLaor mentions is to combine the CreateView
and UpdateView
in one view. In my opinion, it is DRYer. The solution is given here very well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With