How to generate a POST response, with Django REST Framework Bulk?

1

I would like to know what is the way for the Response of a POST with rest_framework_bulk, to be modifiable since by default it always returns the same object or array of object that is sent to it by the service.

model:

class employee():
    name = models.CharField(max_length=4, verbose_name='name')
    profession = models.CharField(max_length=4, verbose_name='profession')
    userCreation = models.ForeignKey(userCreation, verbose_name='user')

    class Meta:
        verbose_name='employee'

    def __unicode__(self):
        return self.name

serializers:

from django.forms import widgets
from .models import employee
from rest_framework import serializers
from rest_framework_bulk import (BulkListSerializer, BulkSerializerMixin, ListBulkCreateUpdateDestroyAPIView,)

class employeeSerializer(BulkSerializerMixin, serializers.ModelSerializer):
    class Meta(object):
        relation_user = serializers.ReadOnlyField(source='user.username')
        model = employee
        fields = ('id', 'name', 'profession', 'relation_user')

view:

from django.shortcuts import render
from .models import employee
from .serializers import employeeSerializer
from rest_framework import generics
from rest_framework_bulk import ListBulkCreateAPIView

class createEmployee(ListBulkCreateAPIView):
    queryset = employee.objects.all()
    serializer_class = employeeSerializer

def perform_create(self, serializer):
    serializer.save(relation_user=self.request.user)

url:

from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from employee import views

urlpatterns = [url(r'^api/createEmployee/$', views.createEmployee.as_view())]

urlpatterns = format_suffix_patterns(urlpatterns)

    def perform_create(self, serializer):
        serializer.save(relation_user=self.request.user)

This works very well and creates the employee without problems, Json who sent the rest service

{
    name: 'Jhon',
    profession: 'Medic'
}

and this is the answer:

{
    name: 'Jhon',
    profession: 'Medic'
}

I would like that in the Response something different could be placed as a sum, a calculation or simply a message that says created employee.

I think with an APIView it would be something like

return Response(succes='Empleado creado con exito')
    
asked by Hansel 20.03.2017 в 21:49
source

3 answers

1

In order to modify / customize the response of the POST request it is necessary to add a response object and set the values with the attributes of the response you want to send.

You must modify your view or view.py file with the following:

from .serializers import personSerilizer
from rest_framework import generics
from rest_framework.response import Response
from rest_framework import status


class createEmployee(generics.CreateAPIView):

    queryset = employee.objects.all()
    serializer_class = employeeSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        self.perform_create(serializer)
        response = {}
        response['success'] = True
        response['message'] = "Registro guardado exitosamente"
        response['status'] = status.HTTP_201_CREATED
        request.data.get('name')}, status=status.HTTP_201_CREATED)
        return Response(response)
    
answered by 18.04.2018 / 17:06
source
0

What you ask is redundant and breaks the principle DRY of Django . What you ask for can be found in the answer itself, in the field status , that when you create an object returns a code, usually the 201 . You can check the status codes in the documentation .

With this answer you can take the measures that you consider appropriate.

from rest_framework import status


if status == status.HTTP_201_CREATED:
    print('Empleado creado con éxito')

Now, answering your question, you can do something like the following:

from rest_framework import status


@api_view(['GET', 'POST'])
def algo(request):
    if request.method == 'POST' and request.status == status.HTTP_201_CREATED:
        return Response({"mensaje": "Empleado creado con éxito", "data": request.data})
    return Response({"message": "Algún mensaje en GET"})
    
answered by 20.03.2017 в 22:15
0

I think I do not understand your question at all, you are using a Serilizer to answer

In the classic restframework django serious

class createEmployee(ListBulkCreateAPIView):
    queryset = employee.objects.all()
    serializer_class = employeeSerializer

    def create(self, request):
        # Llamamos el metodo create del ApiView y es por es donde se crea el objeto
        result = super(createEmployee, self).create(request)
        return Result({'success': True, 'message': 'Creado correctamente'})

Or put it directly in the POST (which I do not recommend because the restframework decorator routers would not work well when using Post), from the Django restframework documentation we have this example.

def post(self, request, format=None):
    serializer = SnippetSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        # return Response(serializer.data, status=status.HTTP_201_CREATED) 
        return Response({'success': True}, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
answered by 21.03.2017 в 20:38