Step 1: Install Required Tools
First, make sure you have the required tools installed in your Python environment:
pip install isort black flake8 pre-commit
Save the dependencies in your requirements.txt
file:
# requirements.txt (28.06.2024)
black==24.4.2
flake8==7.1.0
isort==5.13.2
pre-commit==3.7.1
Step 2: Create a Pre-Commit Configuration File
Create or update a file named .pre-commit-config.yaml
in the root of your project:
# .pre-commit-config.yaml (28.06.2024)
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-added-large-files
- repo: https://github.com/PyCQA/isort
rev: 5.13.2
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: 24.4.2
hooks:
- id: black
- repo: https://github.com/pycqa/flake8
rev: 7.1.0
hooks:
- id: flake8
- repo: local
hooks:
- id: django-check
name: Run Django Check
entry: python manage.py check
language: system
pass_filenames: false
types: [python]
Step 3: Configure flake8
Create or update a setup.cfg
configuration file to customize flake8 and isort
behavior:
_Ensure that isort
is configured to be compatible with black
. isort
has a setting to make it play nicely with black
.
Include the following configuration for isort
to make it work with black
. You can place these settings in an isort
configuration file like .isort.cfg
, pyproject.toml
, or any other configuration file isort
supports._
# setup.cfg (28.06.2024)
[flake8]
max-line-length = 99
exclude = **/migrations/*,venv
extend-ignore = E203, W503
[isort]
profile=black
Step 4: Set up Pre-Commit
Run the following command to set up the pre-commit hooks:
pre-commit install
This command installs the pre-commit hooks defined in your .pre-commit-config.yaml file. Now, every time you try to commit code, the hooks will run automatically to ensure the code adheres to the specified quality checks and formatting rules.
results in something like:
(venv) ➜ project git: ✗ pre-commit install
pre-commit installed at .git/hooks/pre-commit
Step 4.1: Update all pre-commit hooks:
Ensure all hooks are up-to-date by running:
pre-commit autoupdate
Step 5: Running Pre-Commit Manually (Optional)
You can also run the pre-commit hooks manually at any time with the following command:
pre-commit run --all-files
By following these steps, you create a robust pre-commit hook system that enforces code quality and style consistency across your Django project. This helps catch issues early and ensures a more maintainable codebase.
Top comments (0)