Is there a way to combine CreateView and UpdateView?

I want to show the form present in CreateViewif there was no element in the model. Otherwise, I need to show that the form exists in UpdateView. To load already saved values. Later I have to save the data in db by calling the method update_or_create.

Is it possible?

+4
source share
2 answers

Instead of tinkering with a view with a dual purpose, which is not trivial, to figure out when and when to run the correct method (and not recommended), add a third view that will be redirected 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")
+3

" ", @AviahLaor, CreateView UpdateView . -, DRYer. .

0

Source: https://habr.com/ru/post/1630060/


All Articles