In this chapter, we will talk about how to return the response from Django backend back to React Native. To mention, this is Function Based View.
When we were only dealing with html in Django itself, we usually used this return format :
[views.py]
return render(request, "main/register.html", {"form": form})
However, we will this time use Django REST framework(DRF) to send the data as Json format. In this blog, we just show how did we build the code, so please study about DRF more if needed. You need to install rest_framework first as well.
[serializer.py]
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
name = serializers.CharField(max_length=25)
phone = serializers.CharField(max_length=10)
First, we need to make serializer to save data. You can think of serializer as a data basket. Unlike html, we have to change the model data format with serializer first before returning the response. Same as model structure, you can build serializer after making serializer.py file in the same directory.
[views.py]
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .serializer import UserSerializer
@api_view(['GET'])
def get_userinfo(request):
user = User.objects.get(id=request.session['user_id'])
serializer = UserSerializer(data={
'name': user.name,
'phone': user.phone,
})
if serializer.is_valid():
return Response(serializer.data, status=status.HTTP_200_OK)