6

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?

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274

2 Answers2

8

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")
Aviah Laor
  • 3,620
  • 2
  • 22
  • 27
1

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.

Community
  • 1
  • 1
Afrowave
  • 911
  • 9
  • 21