0

I use generic views/class-based views in my project and I want to call some functions if view is done successfully. I use for this def get_success_url() method. But I can't reach the model in that function. How can I get rid of this, or are there any other way to do this?

My codes:

class MyModelUpdate(UpdateView):
    model = MyModel
    fields = ['details']

    def get_success_url(self, **kwargs):
        add_log(form.model, 2, 1, request.POST.user)
        return reverse_lazy('model-detail', kwargs = {'pk' :  self.kwargs['model_id'] })
icanates
  • 5
  • 1

1 Answers1

2

The UpdateView class implements UpdateMixin, which has methods such as form_valid, which is only called if the form data is valid.

So you could do:

class MyModelUpdate(UpdateView):
    model = MyModel
    fields = ['details']

    def get_success_url(self, **kwargs):
         return reverse_lazy('model-detail', kwargs={'pk': self.kwargs['model_id']})

    def form_valid(self, form):
        # The super call to form_valid creates a model instance
        # under self.object.
        response = super(MyModelUpdate, self).form_valid(form)

        # Do custom stuff here...
        add_log(self.object, 2, 1, self.request.POST.user)

        return response
TeaPow
  • 687
  • 8
  • 17