Sławomir Kwiatkowski

by: Sławomir Kwiatkowski

2024/11/17

APIs built with Django Rest Framework with React Client

Content description:
In this post I'll describe how to use APIs created in Django Rest Framework with a React client.
I'll describe how to use tokens generated with JWT.
The created component will renew the token automatically when it expires.
If the token renewal fails (the refresh token has also expired), the login component will be displayed. After successfully logging in with your credentials data, you'll be redirected to the page that invoked the login component.

In the example below I will use a component that displays the warehouses owned by the user.

The useEffect() function runs the fetchWarechouses() function when the page loads.

An attempt is made to download a list of warehouses from the API, and when the result is negative (status 401 - authorization error), a request is made to renew the access token using the refresh token.

If this also fails, the login component is displayed. Additionally, the path to the current page is sent as a parameter, so that you can return to it after a successful login.

2024/11/11

New DRF user API access via React



Content description:
In this post, I will describe how to create a new user via the simple frontend in React.

The following component creates a new user:

     
import { useState } from "react"

function Register() {
    const [username, setUsername] = useState("")
    const [password, setPassword] = useState("")
    const [email, setEmail] = useState("")
    const [profile, setProfile] = useState("client")   

2024/11/03

Django Rest Framework - New User Registration

Content description:
In this post I'll describe how to create a new user.
I'll test creating new user API, sending email to verify the user and resending email if e.g. former token has exipred.

First, I'll make a method where I'll create an inactive user (who cannot log in yet).

     
from ..utils import send_activation_email

class NewUserViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = ContractUserSerializer

    def create(self, request, *args, **kwargs):
        # create user & send email to verify account
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        user = ContractUser.objects.get(username=serializer.data["username"])
        send_activation_email(user, request.build_absolute_uri)
        return Response(serializer.data, status=status.HTTP_201_CREATED)