Coding style¶
Please follow these coding standards when writing code for inclusion in Django.
Python style¶
Please conform to the indentation style dictated in the
.editorconfigfile. We recommend using a text editor withEditorConfig support to avoidindentation and whitespace issues. The Python files use 4 spaces forindentation and the HTML files use 2 spaces.Unless otherwise specified, followPEP 8.
Useflake8 to check for problems in this area. Note that our
setup.cfgfile contains some excluded files (deprecated modules we don’t care aboutcleaning up and some third-party code that Django vendors) as well as someexcluded errors that we don’t consider as gross violations. Remember thatPEP 8 is only a guide, so respect the style of the surrounding code as aprimary 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 119 characters as this is the width of GitHubcode review; anything longer requires horizontal scrolling which makes reviewmore difficult. This check is included when you run
flake8. Documentation,comments, and docstrings should be wrapped at 79 characters, even thoughPEP 8 suggests 72.Use four spaces for indentation.
Use four space hanging indentation rather than vertical alignment:
raiseAttributeError('Here is a multiline error message ''shortened for clarity.')
Instead of:
raiseAttributeError('Here is a multiline error message ''shortened for clarity.')
This makes better use of space and avoids having to realign strings if thelength of the first line changes.
Use single quotes for strings, or a double quote if the string contains asingle quote. Don’t waste time doing unrelated refactoring of existing codeto conform to this style.
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
InitialCapsfor 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). """...
Imports¶
Useisort to automate importsorting using the guidelines below.
Quick start:
$python -m pip install isort >=5.1.0$isort -rc .
...\> py -m pip install isort>= 5.1.0...\> isort -rc .
This runs
isortrecursively 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
importmodulestatements beforefrommoduleimportobjectsin 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¶
In Django template code, put one (and only one) space between the curlybrackets and the tag contents.
Do this:
{{foo}}
Don’t do this:
{{foo}}
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
classMetashould 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):first_name=models.CharField(max_length=20)last_name=models.CharField(max_length=40)classMeta:verbose_name_plural='people'
Don’t do this, either:
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
classMetadef__str__()defsave()defget_absolute_url()- Any custom methods
If
choicesis defined for a given model field, define each choice as alist of tuples, 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'),]
Use ofdjango.conf.settings¶
Modules should not in general use settings stored indjango.conf.settingsat 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.
기타¶
- Mark all strings for internationalization; see thei18ndocumentation for details.
- Remove
importstatements that are no longer used when you change code.flake8 will identify these imports for you. If an unused import needs toremain for backwards-compatibility, mark the end of with#NOQAtosilence 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
AUTHORSfile distributed with Django– not scattered throughout the codebase itself. Feel free to include achange to theAUTHORSfile in your patch if you make more than asingle trivial change.
JavaScript style¶
For details about the JavaScript code style used by Django, seeJavaScript.

