Ignoring Django Migrations in pyproject.toml file for Black formatter

Question:

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.

Asked By: Clark Sandholtz

||

Answers:

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
)/
'''
Answered By: tee

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

- id: black
  exclude: ^.*b(migrations)b.*$
Answered By: Antony Orenge

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

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

'''
Answered By: Elinaldo Monteiro

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
  )/
)
'''
Answered By: maylon

to just extend the default exlusions (without adding the whole list), you can just do:

[tool.black]
extend-exclude = '''
/(
  | migrations
)/
'''
Answered By: fvmac