Django Rest Framework JWT Unit Test

Try setting up a new APIClient for this test. This is how my own test looks like def test_api_jwt(self): url = reverse(‘api-jwt-auth’) u = user_model.objects.create_user(username=”user”, email=”user@foo.com”, password=’pass’) u.is_active = False u.save() resp = self.client.post(url, {’email’:’user@foo.com’, ‘password’:’pass’}, format=”json”) self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST) u.is_active = True u.save() resp = self.client.post(url, {‘username’:’user@foo.com’, ‘password’:’pass’}, format=”json”) self.assertEqual(resp.status_code, status.HTTP_200_OK) self.assertTrue(‘token’ in resp.data) token … Read more

How to return an rest_framework.response object from a django custom middleware class?

I’ve just recently hit this problem. This solution doesn’t use the Django Rest Framework Response, but if your server just returns JSON this solution might work for you. New in django 1.7 or greater is the JSONResponse response type. https://docs.djangoproject.com/en/3.0/ref/request-response/#jsonresponse-objects In the middleware you can return these responses without having all the “No accepted renderers” … Read more

AngularJS + Django Rest Framework + CORS ( CSRF Cookie not showing up in client )

AngularJS Single Page Web Application on Sub-domain A, talking to a Django JSON (REST) API on Sub-domain B using CORS and CSRF protection Since I’m currently working on a similar setup and was battling to get CORS to work properly in combination with CSRF protection, I wanted to share my own learnings here. Setup – … Read more

Django REST Framework – pass extra parameter to actions

In case you can’t/don’t want/whatever install drf-nested-routers, you could achieve the same by doing: @action(detail=True, methods=[‘delete’], url_path=”contacts/(?P<phone_pk>[^/.]+)”) def delete_phone(self, request, phone_pk, pk=None): contact = self.get_object() phone = get_object_or_404(contact.phone_qs, pk=phone_pk) phone.delete() return Response(.., status=status.HTTP_204_NO_CONTENT) The trick is to put the regex in url_path parameter of the decorator and pass it to the decorated method (avoid using … Read more

djangorestframework: Filtering in a related field

I’ll be curious to see a better solution as well. I’ve used a custom method in my serializer to do that. It’s a bit more verbose but at least it’s explicit. Some pseudo code where a GarageSerializer would filter the nested relation of cars: class MyGarageSerializer(…): users = serializers.SerializerMethodField(‘get_cars’) def get_cars(self, garage): cars_queryset = Car.objects.all().filter(Q(garage=garage) … Read more

last_login field is not updated when authenticating using Tokenauthentication in Django Rest Framework

Well, at the end I inherited from the REST Framework TokenAuthentication, pointing to it in the urls file url(r’^api-token-auth/’, back_views.TokenAuthenticationView.as_view()), and the View handles the request and manually calls the update_last_login like this: from django.contrib.auth.models import update_last_login class TokenAuthenticationView(ObtainAuthToken): “””Implementation of ObtainAuthToken with last_login update””” def post(self, request): result = super(TokenAuthenticationView, self).post(request) try: request_user, data … Read more

How to upload multiple files in django rest framework

I manage to solve this issue and I hope it will help community serializers.py: class FileListSerializer ( serializers.Serializer ) : image = serializers.ListField( child=serializers.FileField( max_length=100000, allow_empty_file=False, use_url=False ) ) def create(self, validated_data): blogs=Blogs.objects.latest(‘created_at’) image=validated_data.pop(‘image’) for img in image: photo=Photo.objects.create(image=img,blogs=blogs,**validated_data) return photo class PhotoSerializer(serializers.ModelSerializer): class Meta: model = Photo read_only_fields = (“blogs”,) views.py: class PhotoViewSet(viewsets.ModelViewSet): serializer_class … Read more

Django REST Framework how to specify error code when raising validation error in serializer

You can raise different exceptions like: from rest_framework.exceptions import APIException from django.utils.encoding import force_text from rest_framework import status class CustomValidation(APIException): status_code = status.HTTP_500_INTERNAL_SERVER_ERROR default_detail=”A server error occurred.” def __init__(self, detail, field, status_code): if status_code is not None:self.status_code = status_code if detail is not None: self.detail = {field: force_text(detail)} else: self.detail = {‘detail’: force_text(self.default_detail)} you can … Read more

request.data in DRF vs request.body in Django

You should use request.data. It’s more flexible, covers more use cases and it can be accessed as many times as needed. Quoting the docs: Aboout request.data REST framework introduces a Request object that extends the regular HttpRequest, and provides more flexible request parsing. The core functionality of the Request object is the request.data attribute, which … Read more

Django rest framework override page_size in ViewSet

I fixed this by creating custom pagination class. and setting desired pagesize in class. I have used this class as pagination_class in my viewset. from rest_framework import pagination class ExamplePagination(pagination.PageNumberPagination): page_size = 2 class HobbyCategoryViewSet(viewsets.ModelViewSet): serializer_class = HobbyCategorySerializer queryset = UserHobbyCategory.objects.all() pagination_class=ExamplePagination I am not sure if there is any easier way for this. this … Read more