Possible to have multiple serializers per view using Django Rest Framework - django

As I'm working, my ./views.py is becoming really competitive and I'm wondering if there is a way to refactor it to be DRY. I think in order to do so, I would need the ability to use specify multiple serializers per view.
data would need to be less ambigious so that it actually describes the data it is receiving so that it can be passed into the correct serializer, which would mean it would need to know the API route the received data came from. Not sure how to do that except with a one class per route, how I currently have it setup.
Then there would need to be a way to specify multiple serializers in a view to send the respective data to. Not seeing that this is possible.
# ./urls.py
from .views import (
SecurityQuestionsAPIView,
UserSigninTokenAPIView,
UsernameRecoveryAPIView,
ValidateKeyAPIView
)
urlpatterns = [
url(r'^signin/', UserSigninTokenAPIView.as_view(), name='signin'),
url(r'^verify/', verify_jwt_token),
url(r'^refresh/', refresh_jwt_token),
url(r'^username_recovery/', UsernameRecoveryAPIView.as_view(), name='username_recovery'),
url(r'^validate_key/', ValidateKeyAPIView.as_view(), name='validate_key'),
url(r'^security_questions/', SecurityQuestionsAPIView.as_view(), name='security_questions'),
]
# ./views.py
from .serializers import (
SecurityQuestionsSerializer,
UserSigninTokenSerializer,
UsernameRecoverySerializer,
ValidateKeySerializer
)
# Used for logging into the web application
class UserSigninTokenAPIView(APIView):
permission_classes = [AllowAny]
serializer_class = UserSigninTokenSerializer
def post(self, request, *args, **kwargs):
data = request.data
serializer = UserSigninTokenSerializer(data=data)
if serializer.is_valid(raise_exception=True):
new_data = serializer.data
return Response(new_data, status=HTTP_200_OK)
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
class UsernameRecoveryAPIView(APIView):
permission_classes = [AllowAny]
serializer_class = UsernameRecoverySerializer
def post(self, request, *args, **kwargs):
data = request.data
serializer = UsernameRecoverySerializer(data=data)
if serializer.is_valid(raise_exception=True):
new_data = serializer.data
return Response(new_data, status=HTTP_200_OK)
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
class ValidateKeyAPIView(APIView):
permission_classes = [AllowAny]
serializer_class = ValidateKeySerializer
def post(self, request, *args, **kwargs):
data = request.data
serializer = ValidateKeySerializer(data=data)
if serializer.is_valid(raise_exception=True):
new_data = serializer.data
return Response(new_data, status=HTTP_200_OK)
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
class SecurityQuestionsAPIView(APIView):
permission_classes = [AllowAny]
serializer_class = SecurityQuestionsSerializer
def post(self, request, *args, **kwargs):
data = request.data
serializer = SecurityQuestionsSerializer(data=data)
if serializer.is_valid(raise_exception=True):
new_data = serializer.data
return Response(new_data, status=HTTP_200_OK)
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

You are likely looking for the CreateApiView
class UserSigninTokenAPIView(CreateApiView):
permission_classes = [AllowAny]
serializer_class = UserSigninTokenSerializer
class UsernameRecoveryAPIView(CreateApiView):
permission_classes = [AllowAny]
serializer_class = UsernameRecoverySerializer
class ValidateKeyAPIView(CreateApiView):
permission_classes = [AllowAny]
serializer_class = ValidateKeySerializer
class SecurityQuestionsAPIView(CreateApiView):
permission_classes = [AllowAny]
serializer_class = SecurityQuestionsSerializer

Related

Django rest framework APIView Pagination EmptyPage

Successfully made pagination work and here is my code:
from rest_framework import pagination
class CustomPagination(pagination.PageNumberPagination):
page_size = 10
page_size_query_param = 'page_size'
max_page_size = 10
page_query_param = 'p'
class PaginationHandlerMixin(object):
#property
def paginator(self):
if not hasattr(self, '_paginator'):
if self.pagination_class is None:
self._paginator = None
else:
self._paginator = self.pagination_class()
else:
pass
return self._paginator
def paginate_queryset(self, queryset):
if self.paginator is None:
return None
return self.paginator.paginate_queryset(queryset, self.request, view=self)
def get_paginated_response(self, data):
assert self.paginator is not None
return self.paginator.get_paginated_response(data)
and this my view class:
class OrderOntrackViewPaginated(APIView, PaginationHandlerMixin):
queryset = Order.objects.filter(~Q(staged__iexact="offtrack")).values().order_by('-id')
serializer_class = OrderSerializer
pagination_class = CustomPagination
permission_classes = (permissions.AllowAny,)
http_method_names = ['get']
def get(self, request):
results = self.paginate_queryset(self.queryset)
serializer = self.serializer_class(results, many=True)
return self.get_paginated_response(serializer.data)
my question is if I can handle EmptyPage so if max page is for example 3 and user puts ...?p=4 in the request, I could return a valid response.
I think could be easy to use ListAPIView like this:
from rest_framework.generics import ListAPIView
class OrderOntrackViewPaginated(ListAPIView):
queryset = Order.objects.exclude(staged__iexact="offtrack").order_by('-id')
serializer_class = OrderSerializer
pagination_class = CustomPagination
permission_classes = (permissions.AllowAny,)
http_method_names = ['get']
I hope this help you. Regards!

Range Filter not working in django rest does not react at all when filtered

Range Filter not working in django rest does not react at all when filtered
View
class MDShopListView(generics.ListAPIView):
queryset = smartphone.objects.all()
filter_backends = (DjangoFilterBackend,)
filterset_class = ShoppFilter
def get(self,request):
queryset = self.get_queryset()
serializer=MDShopListSerializer(queryset,many=True)
return Response(serializer.data)
You need to filter the queryset, with self.filter_queryset(…) [drf-doc]:
class MDShopListView(generics.ListAPIView):
queryset = smartphone.objects.all()
filter_backends = (DjangoFilterBackend,)
filterset_class = ShoppFilter
def get(self, request):
queryset = self.filter_queryset(self.get_queryset())
serializer=MDShopListSerializer(queryset,many=True)
return Response(serializer.data)
But actually overriding get(…) is not necessary, since now it does almost exactly what a ListAPIView does by default, except that you do not paginate. Indeed, a ListAPIView is defined as [GitHub]:
class ListAPIView(mixins.ListModelMixin,
GenericAPIView):
"""
Concrete view for listing a queryset.
"""
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
and the .list(…) method is defined in the ListModelMixin as [GitHub]:
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
You thus can define this as:
class MDShopListView(generics.ListAPIView):
queryset = smartphone.objects.all()
filter_backends = (DjangoFilterBackend,)
filterset_class = ShoppFilter
# specify the serializer ↓
serializer_class = MDShopListSerializer

DRF Custom Permission is not firing

I wrote a custom permission class for a drf project to protect my view:
views.py
class Employee(APIView):
permission_classes = [BelongsToClient]
serializer_class = EmployeeSerializer
def get(self, request, pk, format=None):
employee = EmployeeModel.objects.get(pk=pk)
serializer = EmployeeSerializer(employee, many=False)
return Response(serializer.data)
def delete(self, request, pk, format=None):
employee = EmployeeModel.objects.get(pk=pk)
employee.Employees_deleted = True
employee.save()
return Response(status=status.HTTP_200_OK)
My permission class:
permission.py
from rest_framework import permissions
class BelongsToClient(permissions.BasePermission):
message= "You are only authorized to view objects of your client"
"""
Object-level permission to only see objects of the authenticated users client
"""
def has_object_permission(self, request, view, obj):
if obj.Mandant == request.user.Mandant:
return True
else:
return False
Unfortunatly this permission class isn't blocking my view even when it should. I dont know why. Did I miss something?
You need to call check_object_permissions method before response for APIView
class Employee(APIView):
permission_classes = [BelongsToClient]
serializer_class = EmployeeSerializer
def get(self, request, pk, format=None):
employee = EmployeeModel.objects.get(pk=pk)
serializer = EmployeeSerializer(employee, many=False)
self.check_object_permissions(request, employee)
return Response(serializer.data)
has_object_permission only called when you use the DestroyAPIView or RetrieveAPIView or ViewSet.
Try to use a viewset just like below
from rest_framework import viewsets
class Employee(viewsets.ViewSet):
permission_classes = [BelongsToClient]
serializer_class = EmployeeSerializer
def delete(self, request, pk, format=None):
employee = EmployeeModel.objects.get(pk=pk)
self.check_object_permissions(request, employee)
employee.Employees_deleted = True
employee.save()
return Response(status=status.HTTP_200_OK)
Note: I didn't test it but it should work.

DestroyAPIView Django rest validation

class DeleteLedgerCategory(DestroyAPIView):
serializer_class = CategorySerializer
permission_classes = [IsAuthenticated]
def get_queryset(self):
queryset = Category.objects.filter(company = self.request.user.currently_activated_company, id=self.kwargs['pk'])
return queryset
def preform_destroy(self, instance):
if instance.is_default == True:
raise ValueError("Cannot delete default system category")
return instance.delete()
In above class based view. I need to add custom validation error message. ie. if instance.is_default == True: raise error... and only allow to delete the instance if no error encounters. If any unclear question. Do comment
Instead of just raise error you can customize response in destroy method:
from rest_framework.response import Response
class DeleteLedgerCategory(DestroyAPIView):
serializer_class = CategorySerializer
permission_classes = [IsAuthenticated]
def get_queryset(self):
queryset = Category.objects.filter(company = self.request.user.currently_activated_company, id=self.kwargs['pk'])
return queryset
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
if instance.is_default == True:
return Response("Cannot delete default system category", status=status.HTTP_400_BAD_REQUEST)
self.perform_destroy(instance)
You can use the destroy method here but you have to return a response whether it is successful or not
from rest_framework.response import Response
from rest_framework import status
class DeleteLedgerCategory(DestroyAPIView):
serializer_class = CategorySerializer
permission_classes = [IsAuthenticated]
def get_queryset(self):
queryset = Category.objects.filter(company = self.request.user.currently_activated_company, id=self.kwargs['pk'])
return queryset
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
if instance.is_default == True:
return Response("Cannot delete default system category", status=status.HTTP_403_FORBIDDEN)
self.perform_destroy(instance)
return Response(status=status.HTTP_204_NO_CONTENT)

Django REST framework: restricting user access for objects

I'm trying to build a REST API for books:
/api/book
/api/book/{book_id}
A user should have access to his books only. The way I'm doing this now is by filtering the result using username i.e Book.objects.all().filter(owner=request.user)
views.py
class Book_List(APIView):
permission_classes=(permissions.IsAuthenticated)
def get(self, request, format=None):
**books= Book.objects.all().filter(owner=request.user)**
serializer = BookSerializer(books, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = BookSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
#/book/{pk}
class Book_Detail(APIView):
permission_classes = (permissions.IsAuthenticated)
def get_object(self, pk, request):
try:
return Book.objects.get(pk=pk, owner=request.user)
except Playlist.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
book = self.get_object(pk, request)
serializer = BookSerializer(playlist, context={'request': request})
return Response(serializer.data)
def put(self, request, pk, format=None):
book= self.get_object(pk)
serializer = BookSerializer(playlist, data=request.data, context={'request': request})
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
book= self.get_object(pk)
book.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
serializers.py
class BookSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Book
fields = ('url', 'owner','title', 'created_date', 'shared_with', 'tracks')
class UserSerializer(serializers.HyperlinkedModelSerializer):
books = serializers.HyperlinkedRelatedField(many=True,view_name='playlist-detail', read_only=True)
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = User
fields = ('url', 'username', 'owner', 'books')
But is this the correct way?
Does Django Rest Framework provide any in-built solution for this?
Does the solution lie in permissions? If yes, then how do we set it for all objects created by a user (I understand the for getting a particular object we can put a permission check like obj.user==request.user). Am I right?
You could use the ModelViewset, which contains all the logic for the typical CRUD:
class BooksViewSet(ModelViewset):
serializer_class = BookSerializer
permission_classes=[permissions.IsAuthenticated, ]
def get_queryset(self):
return Books.objects.filter(owner=self.request.user)
def perform_create(self, serializer):
serializer.data.owner = self.request.user
super(BooksViewSet, self).perform_create(serializer)