[Django]-Django – how to restrict DeleteView to object owner

0👍

This might not be the best way, but it illustrates the point.

In your views.py, you can access self.get_object() to get the model instance in reference, and then check to see if instance.owner == self.request.user. Look at the source code and try to remain faithful as much possible to the original. All you need is a conditional check.

Something like this:

@method_decorator(login_required, name='dispatch')
class FooDeleteView(DeleteView):
    model = Foo
    success_url = reverse_lazy('index')

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        if self.object.owner != self.request.user:
            return redirect(self.success_url)
        return super().post(request, *args, **kwargs)

If you are curious and would like to know more, you can import pdb and place pdb.set_trace() on the first line of the method, and explore what self is and what methods is available to it. You can do this by callin dir(self) once you inside the method call. You’d be surprised with the amount of things you’d discover.

0👍

You can use a UserPassesTestMixin to achieve this.

class RestaurantDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Restaurant
    template_name = 'restaurant/delete_form.html'
    success_url = '/'
    
    def test_func(self):
        restaurant = self.get_object()
        return restaurant.owner == self.request.user
 
👤fam

Leave a comment