[Answered ]-Django REST API custom methods for generic views

2đź‘Ť

200 vs 400 in this case is mostly preference. 400 means “Bad Request”. This is generally more correct for a incorrectly formatted request, rather than one that doesn’t meet some condition.

200 is just as appropriate it conveys the correct information:

Your request was valid, but I didn’t create a new record.

As to how to do the override. The shortest path is to override the CreateAPIView.create and change the response code used. You should also avoid repeating the default behavior of CreateAPIView by calling super.

class CreateUserView(generics.CreateAPIView):
    model = User
    permission_classes = [permissions.AllowAny]
    serializer_class = NewUserSerializer

    def create(self, request, *args, **kwargs):
        response = super(CreateUserView, self).create(request, *args, **kwargs)
        token, created = Token.objects.get_or_create(user=serializer.instance)
        response.status = status.HTTP_200_OK
        response.data = {'token': token.key}
        return response

Personally, I would have also crafted my NewUserSerializer to have a token field and handle the token so I didn’t have to do that work in the View. It doesn’t belong in a View.

👤John

0đź‘Ť

Save and deletion hooks:

The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.

perform_create(self, serializer) – Called by CreateModelMixin when
saving a new object instance. perform_update(self, serializer) –
Called by UpdateModelMixin when saving an existing object instance.
perform_destroy(self, instance) – Called by DestroyModelMixin when
deleting an object instance.

These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.

https://www.django-rest-framework.org/api-guide/generic-views/#methods

class CourseOrder(generics.CreateAPIView):
    serializer_class = serializers.OrderCoursesSerializer
    permission_classes = [permissions.AllowAny]

    # hook before creating
    def perform_create(self, serializer):
        # print(serializer['name'].value)

        # save post data
        serializer.save()

        try:
            subject, from_email, to = 'New order', 'zelenchyks@gmail.com', 'zelenchyks@gmail.com'
            text_content = 'New order'
            html_content = '''
               <p>client name: %s </p>
               <p>client phone: %s </p>    
                ''' 
                % (serializer['name'].value, serializer['mobile'].value)

            msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
            msg.attach_alternative(html_content, "text/html")
            msg.send()
        except Warning:
            print('Huston we have a problems with smtp')

Leave a comment