Prompt Title: Django viewset object permissions.

Created 1 year ago
Votes 0
Views 303 times
IT
0

Prompt Detail:

Sure, here's an example of how to implement object-level permissions in a Django viewset:

Let's say you have a model called Book:

python
# models.py from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) published_date = models.DateField() is_published = models.BooleanField(default=False)

And you have a viewset for this model:

python
# views.py from rest_framework import viewsets from .serializers import BookSerializer from .models import Book class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer

Now let's say you want to restrict access to certain books based on their is_published status. You can define a permission class that checks this:

python
# permissions.py from rest_framework import permissions class IsPublishedOrAdmin(permissions.BasePermission): def has_object_permission(self, request, view, obj): # allow admins to access all objects if request.user.is_staff: return True # allow non-admins to access published objects only return obj.is_published

Finally, you can apply this permission class to your viewset:

python
# views.py from rest_framework import viewsets from .serializers import BookSerializer from .models import Book from .permissions import IsPublishedOrAdmin class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer permission_classes = [IsPublishedOrAdmin]

Now when a user tries to access a book that is not published, they will receive a 403 Forbidden error unless they are an admin.

avatar
Rashid Mahmood
Shared 2 prompts
Created 1 year ago

Leave a Comment