How customize permissions for updating and deleting objects just for creator (author) in view.py (CRUD classes)? I know classes LoginRequiredMixin and PermissionRequiredMixin, but I cant customize them to make permission just for creator (author) to change exact object. I know how customize permission in DRF using class IsAdminOrReadOnly, for example: permissions.py in DRF
class IsOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return bool(obj.user == request.user or request.user.is_staff)
view.py in Django (without DRF)
class NewsUpdateView(LoginRequiredMixin, BaseMixin, UpdateView):
form_class = NewsForm
model = News
template_name = 'news/news_update.html'
model.py in Django (without DRF)
class News(models.Model):
title = models.CharField(max_length=128)
content = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
photo = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True)
is_published = models.BooleanField(default=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
The question is: How customize permissions in django (not in DRF)? Thank you in advance. I hope you could give me piece of advice, link to the article, or documentation, or example of code to solve this problem. I've read Custom users and permissions, but I haven't got how to solve my exact task.
CodePudding user response:
You can use UserPassesTestMixin
in your view.
from django.contrib.auth.mixins import UserPassesTestMixin
class NewsUpdateView(LoginRequiredMixin, UserPassesTestMixin, BaseMixin, UpdateView):
form_class = NewsForm
model = News
template_name = 'news/news_update.html'
def test_func(self):
news = self.get_object()
return news.user == self.request.user