Restrict user to update model form

I’m using Django auth for my model Dish. Each user manages many dishes (1-n relationship)

# models.py
class Dish(models.Model):
    user_id = models.ForeignKey(User, on_delete=models.CASCADE)
    dish_name = models.CharField(max_length=50)

# views.py
class ProfileFormView(LoginRequiredMixin, UpdateView):
    login_url = '/accounts/login'
    template_name = 'dish.html'
    model = Dish
    success_url = '/dish/updated'

I want to restrict my UpdateView to only dish’s owner (For example: user 1 owns dish 1 and 2; user 2 owns dish 3 and 4. user 1 can edit dish 1, but cannot edit dish 3 or 4)

Assuming that user manages other models (for example: menu, ratings, etc), and they all need to be restricted to their owners. What is the proper way to achieve this?

Thank you very much!

It looks like you’re using the Django CBVs. You’ve got a couple different ways to do this, I’m not sure one is any more “proper” than any other.

What we have done is add the PermissionsRequiredMixin to our classes, and then override the has_permission method to add the appropriate check.

Note, however, that this executes before get_object is called by the view. This could cause an extra query to run, potentially retrieving the same object twice. There are at least two ways to avoid this:

  1. In your has_permission method, save the instance of the object retrieved and override get_object to pull the local copy.
  2. Perform your permission check in get_object, throwing the error if the user is attempting to edit an object they aren’t allowed to.

Ken