Sławomir Kwiatkowski
by: Sławomir Kwiatkowski
2024/12/15
2024/12/01
Fetching a single record from an API using React
Content description:
In this post I'll describe how to get a single warehouse record.
The API is written in Django Rest Framework.
I will use dataLoader to get data from API.
The Warehouse() function uses the loader to obtain data about a specific warehouse. When the loader returns null, the login component is displayed.
import { useEffect } from "react"
import { useLoaderData, useNavigate, useLocation } from "react-router-dom"
function Warehouse() {
const warehouse = useLoaderData()
const navigate = useNavigate()
const location = useLocation()
useEffect(() => {
if (warehouse===null) {
navigate('/login', {state: {"from": location.pathname}})
}
},[]
)
return (
<>
{warehouse &&
<><h1>{warehouse.warehouse_name}</h1>
<h3>{warehouse.warehouse_info}</h3></>}
</>
)
}
The loader function is similar to the function that returns all warehouses belonging to a user:
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)
2024/10/18
Django Rest Framework - API testing
Content description:
In this post I'll describe how to test a ModelViewSet based on the created Contract model.
I'll test the methods: GET, POST, PATCH and DELETE.
I'll check the correctness of the validators and permissions.
I create a Contract model.
The model consists of fields:
- contract status (default: open),
- contract number set by the customer,
- contractor who is to perform the order,
- planned delivery date and time,
- warehouse to which the goods are to be delivered.
The delivery date contains a validator - it cannot be earlier than the order date.
2024/10/02
Django Rest Framework
Content description:
In this post I'll describe how to create a ModelViewSet based on the created Warehouse model. Then I'll describe how to create a serializer for the given model. I'll describe how to create custom permissions for the created ViewSet. Finally I'll make tests for the created API.
First, I make simple Warehouse model with foreign key - a client (the warehouse owner).
from django.db import models
from users.models import ContractUser
class Warehouse(models.Model):
warehouse_name = models.CharField(max_length=15, unique=True)
warehouse_info = models.TextField(max_length=100)
client = models.ForeignKey(ContractUser, on_delete=models.CASCADE)
def __str__(self):
return self.warehouse_name
2024/09/26
Django - new user model & manager
Content description:
In this post I'll describe how to create your own user model in Django.
Then I'll test the model and manager I created.
First, I create a new application called users.
python manage.py startapp users
In the models.py file, I create a custom user that inherits from the AbstractUser class. I add a checkbox in the profile so that a user can be a client or a contractor. A client issues delivery orders to warehouses, and a contractor accepts them.
2024/09/09
Reportlab - creating PDF files
Content description:
Reportlab - generating a PDF on the server
Solved issue: How to generate a pdf file with order details and reservation barcode without saving the file to the server.
Car manager CRUD app - part IV
Content description:
This is the date picker class for the project.
You are free to use it in your projects (MIT license).
The date picker window is an instance of the tk.Toplevel class. I blocked the widgets in the parent window until the date picker window was closed (grab_set() function). The following lines describe the position of the date picker window relative to its parent window. Then an instance of the Calendar class is set up and dp_frame variable was set to hold an instance of the tk.Frame class. Finally, the create_cal_ui() method arranges the widgets in the window.