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.
2024/07/09
Car manager CRUD app - part III
Content description:
In the current post I am adding search box methods (for focus-in, focus-out and to handle text entered into the search box).
I define methods that display windows for creating a new car and for displaying repairs.
The methods for handling the search field are: on_entry_in(), on_entry_out() and on_entry_return().
2024/07/07
Car manager CRUD app - part II
Content description:
In the current post, I create a GUI .
I define the main program window along with the menu bar, toolbar and search box.
I create methods to display all vehicles using a Treeview element, to remove a vehicle and to mark a car as sold.
The car_manager.py file contains the CarManager class. This is a class that inherits from the Frame class from the Tkinter library
When you create an instance of the CarManager class, an instance of the Helper class is created. Then the window name and application icon are set. A shortcut key for exiting the application has been set (Ctrl+x triggers the close_app() method).
2024/07/05
Car manager CRUD app - part I
Content description:
In the current post, I create a Car class that describes the user's vehicles. The class method allows you to easily create instances using a list.
Additionally, I create a file containing SQL code that creates tables in the database and CRUD methods.
In this post, I will describe a simple Python GUI application for recording car repair notes.
No ORM, just simple Python classes with a Tkinter GUI and a bit of SQL (SQLite).
You can download the project code from my Github repository
First, I create a car.py file containing a class describing vehicles.
2024/07/03
Abstract classes in Python
Abstract classes are intended to abstract functionality that will then be implemented in classes that inherit from the abstract class.
The following classes will inherit from the abstract Person class: Intern and Employee
Attempting to create an instance from the abstract Person class will result in a TypeError exception being thrown.
Additionally, not implementing all abstract methods in a child class causes a TypeError exception.
2024/07/02
Property decorator
The concept of object-oriented programming is related to the concept of encapsulation, i.e. hiding class fields and making only public methods (public API) available to read or change the values of these fields.
Python does not support access modifiers. Using private variables like: _variable is just a matter of convention.
However, you can check the validity of the data using the property decorator.
Based on the Employee class code, let's assume that we want to verify the entered telephone number. We would like to check whether it has the appropriate number of digits and does not contain characters that are not digits.
2024/06/29
Basics of Exception Handling in Python
Content description:
- Python exception handling
- Hierarchy of exceptions
- Optional blocks: else and finally
Errors that show up during the execution of the program and are not syntax errors belong to the so-called exceptions.
You can handle these exceptions by putting code that can cause an exception in a try block, and the code to handle the exception in the except block:
Basics of object-oriented programming in Python
- How to create objects in Python
- Inheritance and multi-inheritance
- Extending method code
- Overriding method code
- Init() method
- Class variables
- Class methods, constructor overloading
- Static methods
Let's take a class called Person as an example. By convention, a class name should start with a capital letter, and in the case of a name consisting of many words, we use Pascal formatting - all words written together and starting with a capital letter. The basic class definition is as follows:




