Avinash Raj
Avinash Raj

Reputation: 174706

Is there any way to combine CreateView and UpdateView?

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?

Upvotes: 6

Views: 2281

Answers (2)

Afrowave
Afrowave

Reputation: 940

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.

Upvotes: 1

Aviah Laor
Aviah Laor

Reputation: 3658

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")

Upvotes: 9

Related Questions