标签 react 下的文章

env configuration

on macos or linux , use conda to create a python env

conda create -n django python=3.12

conda activate django

# 查看python版本号是否OK

python --version

Python 3.12.12
# OK

how to select a python version

https://docs.djangoproject.com/zh-hans/5.2/faq/install/#faq-python-version-support

install django

pip install django

base python files

mkdir -p ~/django
cd ~/django

# create a new project named sample
django-admin startproject sample

cd sample

start to run base admin

python ./manage.py runserver
(django) ~/dev/django/sample $ python ./manage.py runserver
#Watching for file changes with StatReloader
#Performing system checks...

#System check identified no issues (0 silenced).

#You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
#Run 'python manage.py migrate' to apply them.
#November 02, 2025 - 10:08:12
#Django version 5.2.7, using settings 'sample.settings'
#Starting development server at http://127.0.0.1:8000/
#Quit the server with CONTROL-C.

#WARNING: This is a development server. Do not use it in a production setting. Use a production WSGI or ASGI server instead.
#For more information on production servers see: https://docs.djangoproject.com/en/5.2/howto/deployment/

add a module such as category

python ./manage.py startapp category

# will create a folder named category and files lie views.py models.py etc.
cd category
ls

(django) ~/dev/django/sample/catalog $ ls
__init__.py admin.py    migrations  tests.py    views.py
__pycache__ apps.py     models.py   urls.py

set url map (route)

https://developer.mozilla.org/zh-CN/docs/Learn_web_development/Extensions/Server-side/Django/skeleton_website

create model (example from appsite)

from django.db import models

# Create your models here.
class CategoryModel(models.Model):
    id = models.AutoField(primary_key=True, verbose_name="自增ID")
    uid = models.CharField(max_length=8, unique=True, null=False, verbose_name="分类ID")
    saasid = models.ForeignKey( to='saas.SaaSModel', to_field='uid', db_column='uid', on_delete=models.CASCADE, null=True, verbose_name="租户ID" )
    alias = models.CharField(max_length=24, unique=True, null=True, verbose_name="别称")

    title = models.CharField(max_length=64, null=False, verbose_name="分类名")
    authorid = models.CharField(max_length=8, null=True, db_index=True, verbose_name="创建人ID")
    parentid = models.CharField(max_length=8, null=True, db_index=True, verbose_name="上一级ID")
    type = models.CharField(max_length=32, null=True, verbose_name="类型")

    description = models.CharField(max_length=256, null=True, verbose_name="描述")
    cover = models.CharField(max_length=256, null=True, verbose_name="封面")

    status = models.CharField(max_length=12, null=False, default='enabled', verbose_name="状态 ")

    createtime = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    lasttime = models.DateTimeField(auto_now=True, verbose_name="最后修改时间")
    featured = models.BooleanField(null=False, default=False, db_index=True, verbose_name="置顶")
    sort = models.IntegerField(null=False, default=0, db_index=True, verbose_name="优先排序")

    class Meta:
        db_table = "item_category"
        verbose_name = "通用分类"
        verbose_name_plural = "通用分类"

    def __str__(self):
        return self.title

    @classmethod
    def list_child(cls, uid, page=1, size=50, sort=None, more_filters=None):
        filters = more_filters if more_filters is not None else {}
        filters['parentid'] = uid
        query = cls.objects.filter(**filters)
        if sort:
            query = query.order_by(sort)
        start = (page - 1) * size
        end = start + size
        return query[start:end]

    @classmethod
    def count_child(cls, uid, more_filters=None):
        filters = more_filters if more_filters is not None else {}
        filters['parentid'] = uid
        return cls.objects.filter(**filters).count()

field types introduction

https://developer.mozilla.org/zh-CN/docs/Learn_web_development/Extensions/Server-side/Django/Models

references

MDN introduction / docs

https://developer.mozilla.org/zh-CN/docs/Learn_web_development/Extensions/Server-side/Django/Introduction

django official docs

https://docs.djangoproject.com/zh-hans/5.2/faq/install/#faq-python-version-support

Conda env

https://shezw.com/note/270/macos_conda

patch libs

ref

    1. install patch-package
npm i patch-package --save-dev
    1. modify the source code in third party libs
    1. generate the .patch
npx patch-package @mantine/core
✔ Created file patches/@mantine+core+7.2.2.patch

remove old source and reinstall

rm -rf node_modules/@mantine/core
bun install 
// npm install

jest

jest can not found canvas

npm i jest-canvas-mock --dev

and add 'canvas' : 'jest-canvas-mock' to moduleNameMapper in jest.config.js.

jest css, svg ...

module.exports = {
    "roots": [
        "<rootDir>",
        "/Users/shezw/dev/web/react/easyvgl-editor"
    ],
    "modulePaths": [
        "<rootDir>",
        "/Users/shezw/dev/web/react/easyvgl-editor"
    ],
    // "moduleDirectories": [
        // "node_modules"
    // ],
    moduleNameMapper: {
        'canvas':'jest-canvas-mock',
        "@mantine/core/styles.css": "<rootDir>/node_modules/@mantine/core/esm/index.css",
        // "@mantine/core/(.*).css": "<rootDir>/node_modules/@mantine/core/esm/$1.css",
    },
    transform: {
        "^.+\\.[t|j]sx?$": "babel-jest",
        "^.+\\App.css$": "jest-transform-css",
        ".+\\.(styl|less|sass|scss|png|jpg|ttf|woff|woff2|svg)$": "jest-transform-stub"
    },
}

jest test throw case

Use a clouse function wrap the test case and check if the result throw an Error.

test('Convert Color to RGBA', ()=>{

    const { toRGBA } = colorConvertor();

    expect( ()=>{ toRGBA("#333444",1000) } ).toThrow(RangeError);
    expect( ()=>{ toRGBA("#333444",-1) } ).toThrow(RangeError);
    expect( ()=>{ toRGBA("#331",50) } ).toThrow(Error);

    expect( toRGBA('#ff3366',100) ).toBe('ff3366ff');
})

jest wrong environment

    The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string.
    Consider using the "jsdom" test environment.

https://jestjs.io/docs/configuration#testenvironment-string

https://jestjs.io/docs/tutorial-react

npm install --save-dev jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer

Jest test fails with "window is not defined"

add globals window to jest.config.js

module.exports = {
    globals: {
        "window": {}
    }
}

TypeError: Cannot read properties of undefined (reading 'html')

npm install --dev jest-environment-jsdom

jsdom environment

    The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string.
    Consider using the "jsdom" test environment.

    ReferenceError: document is not defined
/**
 * @jest-environment jsdom
 */
import '../jest.mock'
import React from 'react';
import {cleanup, render, screen} from '@testing-library/react';
import App from './App';


afterEach(cleanup);
test('Render App', () => {
    // ...
}

Class constructor Stage cannot be invoked without 'new'

use ts-jest instead of jest


TypeError: window.matchMedia is not a function

https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom

src/jest.mock.js

Object.defineProperty(window, 'matchMedia', {
    writable: true,
    value: jest.fn().mockImplementation(query => ({
        matches: false,
        media: query,
        onchange: null,
        addListener: jest.fn(), // deprecated
        removeListener: jest.fn(), // deprecated
        addEventListener: jest.fn(),
        removeEventListener: jest.fn(),
        dispatchEvent: jest.fn(),
    })),
});

xx.test.tsx

import '../jest.mock'