Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
Django

The web framework for perfectionists with deadlines.

Documentación

Help us reach our 2025 fundraising goal!

Donate to theDjango Software Foundation to fund Django's development, security, and community events!
If you got value out of using Django this year, please consider making a donation ♥
Donate today

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 oursetup.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 runflake8. 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 multine error message ''shortened for clarity.')

    Instead of:

    raiseAttributeError('Here is a multine 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 the string contains asingle quote. Don’t waste time doing unrelated refactoring of existing codeto conform to this style.

  • 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()).

  • UseInitialCaps for class names (or for factory functions thatreturn classes).

  • In docstrings, follow the style of existing docstrings andPEP 257.

  • In tests, useassertRaisesMessage() insteadofassertRaises() so you can check the exceptionmessage. UseassertRaisesRegex() only if you needregular expression matching.

  • 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 automateimport sorting using the guidelines below.

    Quick start:

    $ pip install isort$ isort -rc .

    This runsisort 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 allimportmodulestatements 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 lower case 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 calledrequest.

    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)
  • TheclassMeta 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):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
    • classMeta
    • def__str__()
    • defsave()
    • defget_absolute_url()
    • Any custom methods
  • Ifchoices is defined for a given model field, define each choice asa tuple of tuples, with an all-uppercase name as a class attribute on themodel. 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 possible asfollows:

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.

Miscelánea

  • Mark all strings for internationalization; see thei18ndocumentation for details.
  • Removeimport statements 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#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 theAUTHORS 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.

Back to Top

Información Adicional

Support Django!

Support Django!

Contenidos

Obtener ayuda

FAQ
Pruebe las preguntas frecuentes: tiene respuestas a muchas preguntas comunes.
Índice,Índice del módulo, orTabla de Contenidos
Práctico cuando se busca información específica.
Django Discord Server
Join the Django Discord Community.
Official Django Forum
Join the community on the Django Forum.
Ticket tracker
Reporte bugs con Django o con la documentación de Django en nuestro rastreador de tickets.

Descarga:

Fuera de línea (Django 2.0):HTML |PDF |ePub
Proporcionado porLea los documentos.

Diamond and Platinum Members

Sentry
JetBrains
Este documento es para una versión insegura de Django que ya no es compatible. ¡Por favor, actualice a una versión más reciente!

[8]ページ先頭

©2009-2025 Movatter.jp