'Ignoring Django Migrations in pyproject.toml file for Black formatter

I just got Black and Pre-Commit set up for my Django repository.

I used the default config for Black from the tutorial I followed and it's been working great, but I am having trouble excluding my migrations files from it.

Here is the default configuration I've been using:

pyproject.toml

[tool.black]
line-length = 79
include = '\.pyi?$'
exclude = '''
/(
    \.git
  | \.hg
  | \.mypy_cache
  | \.tox
  | \.venv
  | _build
  | buck-out
  | build
  | dist
)/
'''

I used Regex101.com to make sure that ^.*\b(migrations)\b.*$ matched apps/examples/migrations/test.py.

[tool.black]
line-length = 79
include = '\.pyi?$'
exclude = '''
/(
    \.git
  | \.hg
  | \.mypy_cache
  | \.tox
  | \.venv
  | _build
  | buck-out
  | build
  | dist
  | ^.*\b(migrations)\b.*$
)/
'''

When I add that regex line to my config file, and run pre-commit run --all-files, it ignores the .git folder but still formats the migrations files.



Solution 1:[1]

Add the migration exclusion to your .pre-commit-config.yaml file

- id: black
  exclude: ^.*\b(migrations)\b.*$

Solution 2:[2]

That's the solution to the problem: pyproject.toml

[tool.black]
exclude = '''
/(
  | migrations
)/

'''

Solution 3:[3]

Maintaining two different places for exclude config doesn't look good if avoidable and will not work well for the CI either (should you want to dry run black in the PR checks). Adding the following works for the pyproject.toml and then you can run the same in the pre-commit hook and CI:

[tool.black]
...
exclude = '''

(
  /(
    ...
    | .+/migrations
  )/
)
'''

Solution 4:[4]

Try this (note last line):

[tool.black]
line-length = 79
include = '\.pyi?$'
exclude = '''
/(
    \.git
  | \.hg
  | \.mypy_cache
  | \.tox
  | \.venv
  | _build
  | buck-out
  | build
  | dist
  | migrations
)/
'''

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anthony Sottile
Solution 2 Elinaldo Monteiro
Solution 3 maylon
Solution 4 tee