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)