En este tutorial voy a explicar la implementación de un Mixin para dar acceso a una vista solo al usuario que creó el objeto a modificar en esa vista.
mixins.py
from django.core.exceptions import PermissionDenied
classUserPermissionsMixin(object):"""Mixin para verificar si un usuario puede acceder a una vista."""defdispatch(self, request, *args, **kwargs):
model_obj = self.get_object()
ifnot (model_obj.author.id == self.request.user.id or self.request.user.is_staff):
raise PermissionDenied("No tiene acceso.")
return super(UserPermissionsMixin, self).dispatch(request, *args, **kwargs)
Implementacion del mixin en las views.views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import UpdateView, DeleteView
from .models import MyModel
from .mixins import UserPermissionsMixin
from .forms import MyForm
classMyUpdateView(LoginRequiredMixin, UserPermissionsMixin, UpdateView):
login_url = '/login'
model = MyModel
form_class = MyForm
success_url = '/'
classMyDeleteView(LoginRequiredMixin, UserPermissionsMixin, DeleteView):
login_url = '/login'
model = MyModel
success_url = '/'
Lo ultimo que se necesita es un que el modelo tenga un campo author tal que:author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
recuerda importar from django.conf import settings