Home>

Tell me how I can redirect in a functionget_context_data? classUpdateView

Listing:

class UserUpdateView(UpdateView):
    model= user
    fields= [...]
    template_name_suffix= '_update_form'
    def get_context_data(self, **kwargs):
        context= super(UserUpdateView, self).get_context_data(**kwargs)
        if not self.request.user.pk== self.object.pk:
            return redirect('login')
        return context
  • Answer # 1

    No way?

    get_context_datareturns the context to use in the template.

    Better overrideget/post, given that all the necessary data will be there. Below is the source codeDjango

    
    class BaseUpdateView(ModelFormMixin, ProcessFormView):
        """
        Base view for updating an existing object.
        Using this base class requires subclassing to provide a response mixin.
        """
        def get(self, request, *args, **kwargs):
            self.object= self.get_object()
            return super().get(request, *args, **kwargs)
        def post(self, request, *args, **kwargs):
            self.object= self.get_object()
            return super().post(request, *args, **kwargs)
    

    As you can see, you can write

    
        def get(self, request, *args, **kwargs):
            self.object= self.get_object()
            if not request.user.pk== self.object.pk:
                return redirect('login')
            return super().get(request, *args, **kwargs)
    

    And everything will work