- Language:en
Coding style¶
Please follow these coding standards when writing code for inclusion in Django.
Pre-commit checks¶
pre-commit is a framework for managing pre-commithooks. These hooks help to identify simple issues before committing code forreview. By checking for these issues before code review it allows the reviewerto focus on the change itself, and it can also help to reduce the number of CIruns.
To use the tool, first installpre-commit
and then the git hooks:
$python-mpipinstallpre-commit$pre-commitinstall
...\> py -m pip install pre-commit...\> pre-commit install
On the first commitpre-commit
will install the hooks, these areinstalled in their own environments and will take a short while toinstall on the first run. Subsequent checks will be significantly faster.If an error is found an appropriate error message will be displayed.If the error was withblack
orisort
then the tool will go ahead andfix them for you. Review the changes and re-stage for commit if you are happywith them.
Python style¶
All files should be formatted using theblack auto-formatter. Thiswill be run by
pre-commit
if that is configured.The project repository includes an
.editorconfig
file. We recommend usinga text editor withEditorConfig support to avoid indentation andwhitespace issues. The Python files use 4 spaces for indentation and the HTMLfiles use 2 spaces.Unless otherwise specified, followPEP 8.
Useflake8 to check for problems in this area. Note that our
.flake8
file contains some excluded files (deprecated modules we don’tcare about cleaning up and some third-party code that Django vendors) as wellas some excluded errors that we don’t consider as gross violations. RememberthatPEP 8 is only a guide, so respect the style of the surrounding codeas a primary goal.An exception toPEP 8 is our rules on line lengths. Don’t limit lines ofcode to 79 characters if it means the code looks significantly uglier or isharder to read. We allow up to 88 characters as this is the line length usedby
black
. This check is included when you runflake8
. Documentation,comments, and docstrings should be wrapped at 79 characters, even thoughPEP 8 suggests 72.String variable interpolation may use%-formatting,f-strings, or
str.format()
as appropriate, with the goal ofmaximizing code readability.Final judgments of readability are left to the Merger’s discretion. As aguide, f-strings should use only plain variable and property access, withprior local variable assignment for more complex cases:
# Allowedf"hello{user}"f"hello{user.name}"f"hello{self.user.name}"# Disallowedf"hello{get_user()}"f"you are{user.age*365.25} days old"# Allowed with local variable assignmentuser=get_user()f"hello{user}"user_days_old=user.age*365.25f"you are{user_days_old} days old"
f-strings should not be used for any string that may require translation,including error and logging messages. In general
format()
is moreverbose, so the other formatting methods are preferred.Don’t waste time doing unrelated refactoring of existing code to adjust theformatting method.
Avoid use of “we” in comments, e.g. “Loop over” rather than “We loop over”.
Use underscores, not camelCase, for variable, function and method names(i.e.
poll.get_unique_voters()
, notpoll.getUniqueVoters()
).Use
InitialCaps
for class names (or for factory functions thatreturn classes).In docstrings, follow the style of existing docstrings andPEP 257.
In tests, use
assertRaisesMessage()
andassertWarnsMessage()
instead ofassertRaises()
andassertWarns()
so you can check theexception or warning message. UseassertRaisesRegex()
andassertWarnsRegex()
only if you need regularexpression matching.Use
assertIs(…,True/False)
for testingboolean values, rather thanassertTrue()
andassertFalse()
, so you can check the actual booleanvalue, not the truthiness of the expression.In test docstrings, state the expected behavior that each test demonstrates.Don’t include preambles such as “Tests that” or “Ensures that”.
Reserve ticket references for obscure issues where the ticket has additionaldetails that can’t be easily described in docstrings or comments. Include theticket number at the end of a sentence like this:
deftest_foo():""" A test docstring looks like this (#123456). """...
Where applicable, use unpacking generalizations compliant withPEP 448,such as merging mappings (
{**x,**y}
) or sequences ([*a,*b]
). Thisimproves performance, readability, and maintainability while reducing errors.
Imports¶
Useisort to automate import sorting using the guidelines below.
Quick start:
$python-mpipinstall"isort >= 5.1.0"$isort.
...\> py -m pip install"isort >= 5.1.0"...\> isort .
This runs
isort
recursively from your current directory, modifying anyfiles that don’t conform to the guidelines. If you need to have imports outof order (to avoid a circular import, for example) use a comment like this:importmodule# isort:skip
Put imports in these groups: future, standard library, third-party libraries,other Django components, local Django component, try/excepts. Sort lines ineach group alphabetically by the full module name. Place all
importmodule
statements beforefrommoduleimportobjects
in each section. Use absoluteimports for other Django components and relative imports for local components.On each line, alphabetize the items with the upper case items grouped beforethe lowercase items.
Break long lines using parentheses and indent continuation lines by 4 spaces.Include a trailing comma after the last import and put the closingparenthesis on its own line.
Use a single blank line between the last import and any module level code,and use two blank lines above the first function or class.
For example (comments are for explanatory purposes only):
django/contrib/admin/example.py
¶# futurefrom__future__importunicode_literals# standard libraryimportjsonfromitertoolsimportchain# third-partyimportbcrypt# Djangofromdjango.httpimportHttp404fromdjango.http.responseimport(Http404,HttpResponse,HttpResponseNotAllowed,StreamingHttpResponse,cookie,)# local Djangofrom.modelsimportLogEntry# try/excepttry:importyamlexceptImportError:yaml=NoneCONSTANT="foo"classExample:...
Use convenience imports whenever available. For example, do this
fromdjango.viewsimportView
instead of:
fromdjango.views.generic.baseimportView
Template style¶
Follow the below rules in Django template code.
{%extends%}
should be the first non-comment line.Do this:
{%extends"base.html"%}{%blockcontent%}<h1class="font-semibold text-xl">{{pages.title}}</h1>{%endblockcontent%}
Or this:
{# This is a comment #}{%extends"base.html"%}{%blockcontent%}<h1class="font-semibold text-xl">{{pages.title}}</h1>{%endblockcontent%}
Don’t do this:
{%loadi18n%}{%extends"base.html"%}{%blockcontent%}<h1class="font-semibold text-xl">{{pages.title}}</h1>{%endblockcontent%}
Put exactly one space between
{{
, variable contents, and}}
.Do this:
{{user}}
Don’t do this:
{{user}}
In
{%load...%}
, list libraries in alphabetical order.Do this:
{%loadi18nl10tz%}
Don’t do this:
{%loadl10i18ntz%}
Put exactly one space between
{%
, tag contents, and%}
.Do this:
{%loadhumanize%}
Don’t do this:
{%loadhumanize%}
Put the
{%block%}
tag name in the{%endblock%}
tag if it is noton the same line.Do this:
{%blockheader%} Code goes here{%endblockheader%}
Don’t do this:
{%blockheader%} Code goes here{%endblock%}
Inside curly braces, separate tokens by single spaces, except for around the
.
for attribute access and the|
for a filter.Do this:
{%ifuser.name|lower=="admin"%}
Don’t do this:
{%ifuser.name|lower=="admin"%}{{user.name|upper}}
Within a template using
{%extends%}
, avoid indenting top-level{%block%}
tags.Do this:
{%extends"base.html"%}{%blockcontent%}
Don’t do this:
{%extends"base.html"%}{%blockcontent%} ...
View style¶
In Django views, the first parameter in a view function should be called
request
.Do this:
defmy_view(request,foo):...
Don’t do this:
defmy_view(req,foo):...
Model style¶
Field names should be all lowercase, using underscores instead ofcamelCase.
Do this:
classPerson(models.Model):first_name=models.CharField(max_length=20)last_name=models.CharField(max_length=40)
Don’t do this:
classPerson(models.Model):FirstName=models.CharField(max_length=20)Last_Name=models.CharField(max_length=40)
The
classMeta
should appearafter the fields are defined, witha single blank line separating the fields and the class definition.Do this:
classPerson(models.Model):first_name=models.CharField(max_length=20)last_name=models.CharField(max_length=40)classMeta:verbose_name_plural="people"
Don’t do this:
classPerson(models.Model):classMeta:verbose_name_plural="people"first_name=models.CharField(max_length=20)last_name=models.CharField(max_length=40)
The order of model inner classes and standard methods should be asfollows (noting that these are not all required):
All database fields
Custom manager attributes
classMeta
def__str__()
and other Python magic methodsdefsave()
defget_absolute_url()
Any custom methods
If
choices
is defined for a given model field, define each choice as amapping, with an all-uppercase name as a class attribute on the model.Example:classMyModel(models.Model):DIRECTION_UP="U"DIRECTION_DOWN="D"DIRECTION_CHOICES={DIRECTION_UP:"Up",DIRECTION_DOWN:"Down",}
Alternatively, consider usingEnumeration types:
classMyModel(models.Model):classDirection(models.TextChoices):UP="U","Up"DOWN="D","Down"
Use ofdjango.conf.settings
¶
Modules should not in general use settings stored indjango.conf.settings
at the top level (i.e. evaluated when the module is imported). The explanationfor this is as follows:
Manual configuration of settings (i.e. not relying on theDJANGO_SETTINGS_MODULE
environment variable) is allowed and possibleas follows:
fromdjango.confimportsettingssettings.configure({},SOME_SETTING="foo")
However, if any setting is accessed before thesettings.configure
line,this will not work. (Internally,settings
is aLazyObject
whichconfigures itself automatically when the settings are accessed if it has notalready been configured).
So, if there is a module containing some code as follows:
fromdjango.confimportsettingsfromdjango.urlsimportget_callabledefault_foo_view=get_callable(settings.FOO_VIEW)
…then importing this module will cause the settings object to be configured.That means that the ability for third parties to import the module at the toplevel is incompatible with the ability to configure the settings objectmanually, or makes it very difficult in some circumstances.
Instead of the above code, a level of laziness or indirection must be used,such asdjango.utils.functional.LazyObject
,django.utils.functional.lazy()
orlambda
.
Miscellaneous¶
Mark all strings for internationalization; see thei18ndocumentation for details.
Remove
import
statements that are no longer used when you change code.flake8 will identify these imports for you. If an unused import needsto remain for backwards-compatibility, mark the end of with#NOQA
tosilence the flake8 warning.Systematically remove all trailing whitespaces from your code as thoseadd unnecessary bytes, add visual clutter to the patches and can alsooccasionally cause unnecessary merge conflicts. Some IDE’s can beconfigured to automatically remove them and most VCS tools can be set tohighlight them in diff outputs.
Please don’t put your name in the code you contribute. Our policy is tokeep contributors’ names in the
AUTHORS
file distributed with Django– not scattered throughout the codebase itself. Feel free to include achange to theAUTHORS
file in your patch if you make more than asingle trivial change.
JavaScript style¶
For details about the JavaScript code style used by Django, seeJavaScript code.