django-rest-framework-security-filters
Project description
How to install
pip install pip install djangorestframework-security-filters
Why i wrote this project?
I want work easily with roles without multiple ifs in code
How to use
Create role_filters.py with your roles definitions
from rest_framework_role_filters.role_filters import RoleFilter
from .serializers import PostSerializerForUser
class AdminRoleFilter(RoleFilter):
role_id = 'admin'
class UserRoleFilter(RoleFilter):
role_id = 'user'
def get_allowed_actions(self, request, view, obj=None):
# This example returns same list both for "global permissions" check,
# and for "object" permissions, but different list may be returned
# if `obj` argument is not None, and this list will be used to check
# if action is allowed during call to `ViewSet.check_object_permissions`
return ['create', 'list', 'retrieve', 'update', 'partial_update']
def get_queryset(self, request, view, queryset):
queryset = queryset.filter(user=request.user)
return queryset
def get_serializer_class(self, request, view):
return PostSerializerForUser
def get_serializer(self, request, view, serializer_class, *args, **kwargs):
fields = (
'body',
'created_at',
'id',
'serializer_name',
'title',
'updated_at',
'user',
)
return serializer_class(*args, fields=fields, **kwargs)
Create viewset and override get_role_id method
from rest_framework_role_filters.viewsets import RoleFilterModelViewSet
from .models import Post
from .role_filters import AdminRoleFilter, UserRoleFilter
from .serializers import PostSerializer
class PostViewSet(RoleFilterModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
role_filter_classes = [AdminRoleFilter, UserRoleFilter]
def perform_create(self, serializer):
serializer.save(user=self.request.user)
If role_id is ‘admin’:
All actions are allowed
The default queryset is returned -
Post.objects.all()
The default
serializer_class
is used -PostSerializer
The default viewset
get_serializer
method is used
If role_id is ‘user’:
Only actions ‘create’, ‘list’, ‘retrieve’, ‘update’, ‘partial_update’ are allowed
The queryset is filtered by user
The
serializer_class=PostSerializerForUser
is usedThe serializer initializing with
fields
kwargs (e.g. for modified serializer as described in DRF: Dynamically modifying fields)
Check testapp example code implementation.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Hashes for djangorestframework-security-filters-0.1.1.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 55946a081814f25315832b5e68150d08e160a24db2058dd226ca3adbfdb25458 |
|
MD5 | e34e621d99a020d7251b20a2e5503c8d |
|
BLAKE2b-256 | e81b8944a23cd99afca63fa4a830872471f81ea7b943bb0f06333976ac79fb08 |