python
50 lines · 2 tabs
Priya Sharma
Jan 2026
2 tabs
from rest_framework import permissions
class IsOwner(permissions.BasePermission):
"""Allow only object owner to access."""
def has_object_permission(self, request, view, obj):
return obj.owner == request.user
class IsAdminOrReadOnly(permissions.BasePermission):
"""Admins can edit, others read-only."""
def has_permission(self, request, view):
if request.method in permissions.SAFE_METHODS:
return True
return request.user and request.user.is_staff
class HasAPIKey(permissions.BasePermission):
"""Require valid API key in header."""
def has_permission(self, request, view):
api_key = request.META.get('HTTP_X_API_KEY')
if not api_key:
return False
from api.models import APIKey
return APIKey.objects.filter(key=api_key, is_active=True).exists()
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
def get_permissions(self):
"""Different permissions per action."""
if self.action == 'list':
permission_classes = [permissions.AllowAny]
elif self.action == 'create':
permission_classes = [IsAuthenticated]
else:
permission_classes = [IsAuthenticated, IsOwner]
return [permission() for permission in permission_classes]
class AdminViewSet(viewsets.ModelViewSet):
permission_classes = [IsAuthenticated, IsAdminOrReadOnly, HasAPIKey]
2 files · python
Explain with highlit
DRF permissions control access to API endpoints. I use built-in permissions like IsAuthenticated, IsAdminUser, or IsAuthenticatedOrReadOnly. For custom logic, I create permission classes implementing has_permission() and has_object_permission(). I combine multiple permissions with lists. Permissions run before views, short-circuiting unauthorized requests. For object-level permissions, I check ownership or roles. I use different permissions per action with get_permissions(). This provides fine-grained API access control separate from Django's auth system.
Related snips
python
import os
import stat
for root, _dirs, files in os.walk('/etc'):
for name in files:
path = os.path.join(root, name)
Python security audit script for exposed risky filesystem state
python
auditing
host-security
by Kai Nakamura
1 tab
python
class Product(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
cost = models.DecimalField(max_digits=10, decimal_places=2)
margin = models.DecimalField(max_digits=5, decimal_places=2, blank=True)
Django model signals vs overriding save
django
python
models
by Priya Sharma
2 tabs
python
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
Django URL namespacing and reverse lookups
django
python
urls
by Priya Sharma
3 tabs
python
import graphene
from graphene_django import DjangoObjectType
from blog.models import Post, Comment
class PostType(DjangoObjectType):
Django GraphQL with Graphene
django
python
graphql
by Priya Sharma
2 tabs
python
from django.db.models import Count, Avg, Sum, Q, F
from django.views.generic import TemplateView
from products.models import Product, Order, OrderItem
class DashboardView(TemplateView):
Django aggregation with annotate for statistics
django
python
database
by Priya Sharma
1 tab
python
from django.db import models
from django.utils.text import slugify
class Article(models.Model):
title = models.CharField(max_length=200)
Django model save override for custom logic
django
python
models
by Priya Sharma
1 tab
Share this code
Here's the card — post it anywhere.