Skip to content

Instantly share code, notes, and snippets.

@TechRancher
Created July 25, 2020 00:57
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save TechRancher/6440451a05797d8e1c61642347ca6b69 to your computer and use it in GitHub Desktop.
Save TechRancher/6440451a05797d8e1c61642347ca6b69 to your computer and use it in GitHub Desktop.
Coding Style For Django Plus Best Practice Coding Tips

Coding Style For Django

Please follow these coding standards when writing code for inclusion in Django. - Django Documentation

Python Style

  • Use EditorConfig or conform to the indentation style dictated in the .editorconfig file
  • Use 4 spaces for indentation with Python and 2 indentation spaces for HTML files.
  • Use PEP 8 Python style as a guide
  • Use flake8 to check for problems in this area. But Django has line lengths rules that are different then PEP 8 recommends.
  • Use four space hanging indentation rather than vertical alignment:
# Not like this way:
raise AttributeError('Here is a multiline error message '
                    'shortened for clarity.')

# Try it this way
raise AttributeError(
    'Here is a multiline error message '
    'shortened for clarity.'
)
  • Use single quotes for strings, or a double quote if the string contains a single quote.
  • Use underscores, not camelCase, for variable, function and method names
  • Use InitialCaps for class names (or for factory functions that return classes)
  • Use in tests, assertRaiseMessage() and assertWarnsMessage() instead of assertRaises() and assertWarns() to check for the exception or warning message

Imports

  • Use isort to automate import sorting into these groups:
    future, standard library, third-party libraries, other Django components, local Django component, try/excepts.
$ python -m pip install isort
installed info will be displayed here
$ isort -rc .
  • This runs isort recursively from your current directory, modifying any files that don't conform to the guidelines. If you need your imports out of order to avoid a circular import use a comment like this:
import module # isort:skip

example django/contrib/admin/example.py

# future
from __future__ import unicode_literals

#standard library
import json
from itertools import chain

# third-party
import bcrypt

# Django
from django.http import Http404
from django.http.response import (
    Http404, HttpResponse, HttpResponseNotAllowed, StreamingHttpResponse, cookie,
)

# local Django
from .models import LogEntry

# try/except
try:
    import yaml
except ImportError:
    yaml = None

CONSTANT = 'foo'



class Example:
    # ...
  • Use convenience imports whenever available
# Instead of this:
from django.views.generic.base import View

# Do this:
from django.views import View

Template Style

  • When using Django template code, put one space between the curly brackets and the tag contents.
# Not like this:
{{foo}}

# Do this:
{{ foo }}

View Style

  • Using Django views, the first parameter in a view function should be called request.
# This is not right:
def my_view(req, foo):
    # ...

# Now this is better:
def my_view(request, foo):
    # ...

Model View

  • Field names should be all lowercase, using underscores instead of camelCase.
# This does not look good:
class Person(models.Model):
    FirstName = models.CharField(max_length=20)
    Last_Name = models.CharField(max_length=40)

# Looks way better:
class Person(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=40)
  • class Meta should appear after the fields are defined. Put a single blank line to separate the fields and the class definition. The order of the model inner classes and standard methods should be:

  • All database fields

  • Custom manager attributes

  • class Meta

  • def str()

  • def save()

  • def get_absolute_url()

  • Any custom methods

# Not like this example:
class Person(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=40)
    class Meta:
        verbose_name_plural = 'people'

# This is not the right way either
class Person(models.Model):
    class Meta:
        verbose_name_plural = 'people'

    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=40)

# This is the way to do it:
class Person(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=40)

    class Meta:
        verbose_name_plural = 'people'
  • If using choices for a given model field, define each choice as a list of tuples, with an all-uppercase name as a class attribute on the model.
# Example with model field that has choices defined in it.
class MyModel(models.Model):
    DIRECTION_UP ='U'
    DIRECTION_DOWN = 'D'
    DIRECTION_CHOICES = [
        (DIRECTION_UP, 'Up'),
        (DIRECTION_DOWN, 'Down'),
    ]

Tips For Best Practice Coding

  1. Avoid abbreviating variable names.
  2. Write out your function argument names. As we addressed above.
  3. Document your classes and methods. Your work now will pay in the future.
  4. Comment your code. This is good but it is more important to document your classes and methods.
  5. Refactor repeated lines of code into reusable functions or methods.
  6. Try to keep your functions and methods short.
  7. Use flake8 to check your code quality as we talked about at the beginning of this list.
  8. Use explicit relative imports to avoid program bloat.
  9. Avoid using import *
  10. Use underscores in URL pattern names instead of dashes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment