Learning summary of Django official code style guide

Time:2020-4-23

Python style

  • Not mentioned in the following, all follow Python’s pep8 convention. See the Python code style guide pep8 summary.

PEP 8 limits the president to a maximum of 79 characters, but Django allows a maximum of 119 characters (this is the width allowed by the GitHub code review tool). PEP 8 limits the length of documents, comments and docstrings to 72 characters, while Django limits them to 79 characters.

Use flake8 to check code quality.

  • Use 4 spaces for each level of indentation
  • Underline in variable, function and method names_, notcamelCase, if it should be written aspoll.get_unique_voters()Instead of writingpoll.getUniqueVoters()
  • Class name and factory function name of return class should beInitiaCapsform
  • Use convenientimportFor example, usingfrom django.views.generic import ViewInstead of usingfrom django.views.generic.base import View
  • In docstring, use “action statement”, such as:
#Use as follows:
def foo():
    """
    Calculates something and returns the result.
    """
    pass
#Do not use:
def foo():
    """
    Calculate something and return the result.
    """
    pass

Template style

  • There is only one space on both sides of the label content, such as{{ foo }}, not{{foo}}

View style

  • The first argument to the view function should berequestSuch asdef my_view(request, foo):Instead of usingdef my_view(req, foo):

Data model style

  • Data item names should be all lowercase, underlined instead ofcamelCase, such as:
#Right style:
class Person(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=40)
#Wrong style:
class Person(models.Model):
    FirstName = models.CharField(max_length=20)
    Last_Name = models.CharField(max_length=40)
  • class MetaIt should be placed after the data item definition and separated by a blank row, such as:
#Right style:
class Person(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=40)

    class Meta:
        verbose_name_plural = 'people'
#Don't write like this:
class Person(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=40)
    class Meta:
        verbose_name_plural = 'people'
#Don't write like that
class Person(models.Model):
    class Meta:
        verbose_name_plural = 'people'

    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=40)
  • If defined__str__(before supporting Python 3, it was__unicode__), should be used on the class of the data modelpython_2_unicode_compatible()Decorator.
  • Layout order in data model class:

    1. Data item definition
    2. Customized Manager
    3. class Meta
    4. def __str__()
    5. def save()
    6. def get_absolute_url()
    7. Other customization methods
  • choicesThe tuple should be defined as a tuple, and the option name of a single character should be set as an attribute in the class, because it is a constant and uses the full uppercase style, such as:
class MyModel(models.Model):
    DIRECTION_UP = 'U'
    DIRECTION_DOWN = 'D'
    DIRECTION_CHOICES = (
        (DIRECTION_UP, 'Up'),
        (DIRECTION_DOWN, 'Down'),
    )

Use of django.conf.settings

Do not access at the top level of the module (the part that will execute automatically when the module is imported)django.conf.settings。 Django projects can only calldjango.conf.settings.configure()Function once (only once) to configure settings. Settings is aLazyObjectObject, which is only called when accesseddjango.config.settings.configure()To configure settings.

If it is accessed at the top level of the module, it will automatically complete thedjango.conf.settings.configure(), which will affect the configuration of subsequent settings.

Other

  • All strings should be internationalized
  • As the code evolves, remove the unusedimport, flake8 will not be usedimportDisplay the warning message. If you want to remove it, add it at the end of the code line# NOQA
  • Remove extra white space at end of line
  • Do not write the contributor’s name in the code, but in a separateAUTHORSIn file

Reference: Django coding style