Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 209
Avinash Raj Avatar asked Feb 23 '16 12:02

Avinash Raj


2 Answers

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")
like image 90
Aviah Laor Avatar answered Nov 12 '22 23:11

Aviah Laor


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.

like image 1
Afrowave Avatar answered Nov 12 '22 23:11

Afrowave