Skip to content

Instantly share code, notes, and snippets.

@sae13
Created June 21, 2020 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sae13/bd10c8a8265db17f0a18a81fc04ac943 to your computer and use it in GitHub Desktop.
Save sae13/bd10c8a8265db17f0a18a81fc04ac943 to your computer and use it in GitHub Desktop.
import django_filters
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, CreateModelMixin, DestroyModelMixin, \
UpdateModelMixin
from rest_framework.request import Request
from rest_framework.response import Response
class ProjectCustomGenericApiViewListCreate(GenericAPIView,
ListModelMixin,
CreateModelMixin,
):
# serializer_class = ComplexSerializer
# queryset = Profile.objects.all()
# lookup_field = 'id'
permission_name_str = False
allow_view = False
def perform_create(self, serializer):
try:
serializer.save(create_by=self.request.user.username)
except Exception:
pass
serializer.save()
def get(self, request: Request):
if not self.allow_view:
if not self.permission_name_str:
self.permission_name_str = self.__class__.__name__[:-18]
content_type = ContentType.objects.get_for_model(self.get_serializer().Meta.model)
view_permission = "{}.view_{}".format(content_type.app_label, content_type.model)
user: User = request.user
if not user.is_superuser and not user.has_perm(view_permission):
return Response(status=status.HTTP_401_UNAUTHORIZED)
return self.list(request)
def post(self, request: Request):
return self.create(request)
class ProjectCustomGenericApiViewCRUD(GenericAPIView, RetrieveModelMixin, DestroyModelMixin,
UpdateModelMixin):
lookup_field = 'id'
permission_name_str = False
allow_view = False
def perform_update(self, serializer):
instance = serializer.save()
try:
instance.last_modify_by = self.request.user.username
instance.save()
except Exception:
pass
def get(self, request: Request, id):
if not self.allow_view:
if not self.permission_name_str:
self.permission_name_str = self.__class__.__name__[:-18]
content_type = ContentType.objects.get_for_model(self.get_serializer().Meta.model)
view_permission = "{}.view_{}".format(content_type.app_label, content_type.model)
user: User = request.user
if not user.is_superuser and not user.has_perm(view_permission):
return Response(status=status.HTTP_401_UNAUTHORIZED)
return self.retrieve(request)
def delete(self, request: Request, id):
return self.destroy(request)
Response(status=status.HTTP_404_NOT_FOUND)
def put(self, request: Request, id):
return self.update(request)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment