How to allow UpdateView only to a user that owns that model - and that model is already connected with a foreign key

I want the Topping model to only be accessible to a current user, and not to other users who could access that page by copying the URL.

models.py

class Pizza(models.Model):
    name = models.CharField(max_length=20)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    def __str__(self):
      return self.name
    def get_absolute_url(self):
      return "/pizzas"

class Topping(models.Model):
    pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE)
    name = models.CharField(max_length=20)
    def __str__(self):
      return self.name
    def get_absolute_url(self):
       return reverse("pizza", kwargs={"pizza_id": self.pizza.pk})

views.py

class UpdateTopping(LoginRequiredMixin, UpdateView):
    model = Topping
    form_class = UpdateToppingForm
    template_name = "pizzas/update_topping.html"

Something along these lines (this has worked on the primary model):

class UpdatePizza(LoginRequiredMixin, UpdateView):
    model = Pizza
    form_class = UpdatePizzaForm
    template_name = "pizzas/update_pizza.html"
    def get_queryset(self): 
        base_qs = super(UpdatePizza, self).get_queryset()
        return base_qs.filter(owner=self.request.user)

You can do something like this:

from django.core.exceptions import PermissionDenied

class UpdateTopping(LoginRequiredMixin, UpdateView):
    model = Topping
    form_class = UpdateToppingForm
    template_name = "pizzas/update_topping.html"

    def form_valid(self, form):
        if self.request.user != form.cleaned_data['pizza'].user:
            raise PermissionDenied(f"You are not allowed to edit this topping.")
Back to Top