Sławomir Kwiatkowski

by: Sławomir Kwiatkowski

2025/02/18

Material UI - Select component and React



Content description:
In this post I'll describe how use Select component with React

By placing a label variable in the Select component, the label will not be displayed. Only an empty field will appear.

2025/02/09

useContext hook



Content description:
In this post, I will describe how to use the useContext hook to display appropriate links depending on whether the user is already logged in or not.
If you are not logged in, the navigation bar will display Login and Register links, and after a successful login, a Logout link will be displayed.

2025/01/05

Creating and editing a warehouse - React frontend for DRF API

Content description:
In this article, I'll show you how to create a new warehouse and edit an existing one using a front-end built in React (the back-end API was built in DRF).

First, I add the components of the pages responsible for creating a new warehouse and editing an existing one to the router in the main App.jsx component.

     
import WarehouseAddPage from "./pages/WarehouseAddPage"
import WarehouseEditPage from "./pages/WarehouseEditPage"
import { warehouseLoader } from "./components/Warehouse"

const router = createBrowserRouter(
  createRoutesFromElements(
    <Route path="/" element={<MainLayout/>}>
      <Route index element={<MainPage/>} />
      <Route path="/login/" element={<LoginPage/>} />
      <Route path="/logout" element={<LogoutPage/>} />
      <Route path="/register" element={<RegisterPage/>} />
      <Route path="/warehouses" element={<WarehousesPage/>} />
      <Route path="/warehouses/:id" element={<WarehousePage/>} loader={warehouseLoader} />
      <Route path="/add-warehouse" element={<WarehouseAddPage/>} />
      <Route path="/edit-warehouse/:id" element={<WarehouseEditPage/>} loader={warehouseLoader} />
      <Route path="*" element={<ErrorPage/>} />
    </Route>
  )
)

function App() {
  return (
    <RouterProvider router={router} /> 
  )
}

export default App

2024/12/15

Tkinter and Pandas - Excel file from a gas station

Content description:
In this article I'll describe using Tkinter and Pandas to display a refueling report received from a gas station in xlsx format.
GUI class defined using tkinter in a separate file.
Excel file loaded using Pandas library - how to perform data searching and aggregation.

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