1

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?

8
  • Have you checked this, Django Forms with ReactJS seems it would be helpful to you. Commented Jul 16, 2021 at 4:18
  • Ok! But this gives the fields to render the form. I want to use the django built in validation in my form. Commented Jul 16, 2021 at 4:21
  • @sagar_v_p because if a validation error occurs like the password is common, how will react know it? Commented Jul 16, 2021 at 4:30
  • React will know after the form is sent to your API endpoint. However if you want the validation to happen before the form is sent, then you'd need to expose another API endpoint that takes in the password and have Django run its password validation in the serializer or view. In both cases, you'll need to write your API serializers, views, and configure your URL endpoints. Commented Jul 16, 2021 at 5:17
  • Ok! So how do I tell django to do the validation? Commented Jul 16, 2021 at 5:31

1 Answer 1

2

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')
Sign up to request clarification or add additional context in comments.

5 Comments

Ok, thank you! It returns an error if password is not fine but how can I get the reason for why the password did not pass the validation test?
Hello @Pythony for individual field validation check this post stackoverflow.com/a/36419160/14457833
How to create the UserSerializer?
Hello @Pythony check I've edited my answer added UserSerializer
Ok, thanks! If I return something other than UserSerializer like {"user": "successful"} will there be any problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.