Skip to content
Advertisement

Serve Django views with React?

I am making a web application with react as frontend and django-rest-framework as backend.

For django, I am following a tutorial. https://www.techwithtim.net/tutorials/django/user-registration/ – here they have made a registration form with django that has proper validation.

Is there a way to do the same with React? Essentially, is there a way to show Django templates and views with React? If not, should I just link to the specific Django page hosted on the Django server?

Advertisement

Answer

First you have to create serializers for your login and registration view like this

from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth import authenticate

# Register Serializer
class RegisterSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'password')
        extra_kwarg = {'password':{'write_only':True}}

    def create(self, validated_data):
        user = User.objects.create_user(
            validated_data['username'],
            validated_data['email'],
            validated_data['password']
            )
        return user

# Login Serializer

class LoginSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()

    def validate(self, data):
        user = authenticate(**data)
        if user and user.is_active:
            return user
        raise serializers.ValidationError("Incorrect Credentials")

and inside your views.py you have to create view like this

from rest_framework import generics
from rest_framework.response import Response
from .serializers import RegisterSerializer, LoginSerializer

# Register API
class RegisterAPI(generics.GenericAPIView):
    #I'm using generic view you can create your custom view
    serializer_class = RegisterSerializer
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        #here your data get validated and throw ValidationError to your API endpoint
        user = serializer.save()
        return Response({
            "user":UserSerializer(user, context=self.get_serializer_context()).data})

# Login API
class LoginAPI(generics.GenericAPIView):
    serializer_class = LoginSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data
        return Response({
            "user":UserSerializer(user, context=self.get_serializer_context()).data})

and you have to create endpoint for this to connect your frontend to you backend

urls.py

from django.urls import path
from .api import RegisterAPI, LoginAPI

urlpatterns = [
    path('api/auth/register', RegisterAPI.as_view()),
    path('api/auth/login', LoginAPI.as_view()),
]

and than you have to call a method in you frontend application onSubmit or whatever you want

onSubmit = e => {
        e.preventDefault();
        const {username, email, password} = this.state; //you have to create state I've not provided because it will be to big code
        const login = {name, email, password};
        this.Login(login);//this method you have to create to fetch data to your endpoint and it will give you a response 
        this.setState({
            name:'',
            email:'',
            password:''
        });
    };

from Login method you will receive a response from that response you have to access alll the error in .catch() method like this

.catch(err => {
  const errorText = err.response.data,
  const errorStatus = err.response.status
});

I think this is lot of code so I’ll stop here any more info I’ll provide you a tutorial URL.

UPDATE

UserSerializer

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email')
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement