Django REST framework with JWT Authentication(part-2)

 Django REST framework with JWT Authentication(part-1)

GITHUB : CLICK ME

 

Hello Mates, we are here again for part 2, so what we do today?

  • Register api view
  • Login api view

 Let's Start with register view:

so we begin with serializers:

What is data serialization? 

Data serialization is the process of converting structured data to a format that allows sharing or storage of the data in a form that allows recovery of its original structure. In some cases, the secondary intention of data serialization is to minimize the data’s size which then reduces disk space or bandwidth requirements.

create a serializers.py file inside accounts app and our codes lookes like this.

 
from rest_framework import serializers
from django.contrib.auth import get_user_model

User = get_user_model()
""" [Register View]
    Creating new user
    
"""
class RegisterSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id''username''email''password']
        extra_kwargs = {'password': {'write_only'True}}

    def create(selfvalidated_data):
        password = validated_data.pop("password"None)
        instance = self.Meta.model(**validated_data)
        if password is not None:
            instance.set_password(password)
        instance.save()
        return instance
 

Now let's move to views.py:

from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework import exceptionsstatus
from rest_framework.response import Response

from .serializers import RegisterSerializer

@api_view(['POST'])
def register_view(request, *args, **kwargs):
    data = request.data
    if data['password'] != data['password_confirm']:
        raise exceptions.APIException("Password Does not match")

    serializer = RegisterSerializer(data=data)
    serializer.is_valid(raise_exception=True)
    serializer.save()
    return Response(
        {'data'serializer.data}, 
        status=status.HTTP_201_CREATED
        )

 now we create our urls.py

 
from django.urls import path
from .views import register_view

urlpatterns = [
    path('register/'register_viewname="register")
]

Let's test our register_api with postman ‼️

Hoorah  🙌🏻 🙌🏻 🙌🏻 🙌🏻 🙌🏻 we are finished here..... see you on next one.... chao...

⏭️See Part 3⏭️


 

 

Post a Comment

Previous Post Next Post