Django & React-Native: Django response back to RN

Shawnpy·2021년 9월 22일
0

Django & React-Native

목록 보기
6/14

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

[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.

FBV with Serializer


[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)

Use api_view()

  • api_view() is necessary to interact with React Native. You can refer to the documentation, but mostly import it, and put the request type in the parameter.

Put data into serializer

  • Once you retrieve data and organized, you can put the data into the serializer. Data format is dictionary, and you may refer to the sample code above.

return Response

  • When the serializer is valid with the serializer format(ex. CharField(max_length=25)), return the data inside of serializer back to React Native by Response from rest_framework.response. You can set the status at the same time.
profile
Do what you feel now

0개의 댓글