Django best practices

Good Django code of practice, from Github: https://github.com/brantyoung/zh-django-best-practices/blob/master/readme.rst/

Django best practices - Chinese version (2009-06-17)

Be careful:

Note: English Guide (django-best-practices) for a long time not update, this text content may be outdated, only for reference, not used as a development criterion.

Translation:

brantyoung

The project home page:

The translator (yospaly)

Django   best practices (django-best-practices);   `django-reusable-app-docs`_  a branch of the project, it was extended in the original project ideas, set up on the Django Web development of the "best practices" rules, these ideas beyond the scope of official documents.

This document consists of a series of standards, the how to create convenient maintenance, code clean, clear structure, easy reuse, easy to deploy Django projects. For beginners, it is a rare guide, if you don't know where to start, according to documents that can regulate quickly; for experienced Django master, it also has certain reference value, can be used to create your own best practice standards.

The original is a multi page, but     not too many of each rule, break it up into multiple pages instead of browsing inconvenient. So I put them all into a single page, in addition, no other changes.

The original and the translation of the source files are using   reStructuredText  format, can use   Sphinx  converted into HTML format documents.

Note

Chinese version and English version to keep synchronous updates the current version of 2009-06-17 11:32:35.

Django best practices

This is a report on the development and deployment of   Django Web framework;   dynamic document (will be updated at any time). These guidelines should not be considered absolutely correct     or   only   use the Django method, it should be said that these best practice is that we use the framework of the experience accumulated over the years.

This project is   django-reusable-app-docs   a branch, the excellent project by   Brian Rosner  and   Eric Holscher  the establishment, is about how to develop and maintain the best practice reuse Django apps criteria.

Note

This document source code on the GitHub  django-best-practices , can use   Sphinx  converted into a variety of document formats

Code style

In general, the code should be clean, concise, easy to read.  The Zen of Python (PEP 20)   is the authoritative introduction Python coding practices.

The application of Django (app)

How to publish my app ?

Django should use the standard   Python Package Index  Pypi and Cheese Shop. I wrote an article on how to easily packaged and upload the app to the Pypi tutorial.

If you upload app to Pypi, preferably in your project name before the "django-" prefix.

(yospaly: did not understand its meaning, hope master pointing) Also note, that when below when we refer to the default place for something as a file, that also means that you can make a directory of that same name; as per normal python.

File

What is the reuse of app?

A Django app, one can be easily embedded into project app, provides a very clear function. They should focus on and follow the Unix Philosophy -- "do one thing and do it well". For more information please refer to the James Bennett Djangocon talk.

The Application module

(yospaly: all uppercase words, such as: APP, MODEL, replaced with real app name or model name. Your project)

Admin

  • Non essential
  • In your APP/admin.py file
  • The Admin MODEL class named MODELAdmin

Context processor

  • In your APP/context_processors.py file

A content source

  • In your APP/feeds.py file

Form

  • In your APP/forms.py file

Managers

  • In your APP/managers.py file

Middleware

  • In your APP/middleware.py file
  • To achieve the tasks as few as possible

Model

  • In the APP/models (.Py file or directory)
  • Follow the   agreement; Django's model

Template

  • In your APP/templates/APP/template.html file

In order to standard Django template block (block) name, I recommend the following block usually name.

  • {% block title %}

This block is used to define the page title. Your base.html template is likely to define the site name in the tag (Site's name) (even if the use of the Sites framework), in order to be able to put on all pages.

  • {% block extra_head %}

I think this is a very useful block, a lot of people have been in some way in use. Many pages often need to add some information in the HTML document header, such as RSS, Javascript, CSS, and the other should be placed in the document header information. You can, also may be defined in addition, special block (for example, in front of the title block) in other parts of the information added to the document header.

  • {% block body %}

The tag to the body part page. This allows you to create in the app of the page to replace the contents of the whole page, is not only the content of the text. This kind of practice is not common, but when you need it, it really is a very convenient tag. maybe you haven't noticed, I always as far as possible. The tag name and the HTML tag names remain the same.

  • {% block menu %}

Your menu (navigation) should be included in this block. It is aimed at the site level navigation, not every page exclusive navigation menu.

  • {% block content %}

This block is used for placing the page text content. Any page text content may not be the same. It does not contain any site navigation, header, footer, or any other base template stuff.

Other possible block
  • {% block content_title %}

Used to specify the content block "title". For example the blog title. Also can be used to contain content navigation (for example: Outline), or other similar stuff. Generally are not the main contents about page stuff. I don't know whether the block should be placed in the content tag, and corresponds to the previously suggested content tag, is it right? Also need a main_content block.

  • {% block header %} {% block footer %}

Page footer text area and any each page may change.

  • {% block body_id %} {% block body_class %}

Used to set the HTML document body tab of the class or ID properties. Very useful in setting the style or other attributes.

  • {% block [section]_menu %} {% block page_menu %}

This is corresponding to the previously proposed menu block. Used to navigate a chapter or page.

Template tags

  • In your APP/templatetags/APP_tags.py file
The recommended template tag syntax
  • as (Context Var): This is used to set a variable in the context of the page
  • for (object or app.model): This is used to designate an object for an action to be taken on.
  • limit (num): This is used to limit a result to a certain number of results.
  • exclude (object or pk): The same as for, but is used to exclude things of that type.

Test

  • In the APP/tests (.Py file or directory).
  • Fixtures is placed in the APP/fixtures/fixture.json file
  • Usually just rewrite Django testcase

URLs

  • In the APP/urls (.Py file or directory).
  • Set the name property to be counter check; the name property is set to APP_MODEL_VIEW format, such as blog_post_detail or blog_post_list.

View

  • In the APP/views (.Py file or directory).
  • Can be any calls the python function.
  • View parameters should provide reasonable defaults, and easy to customize:

Example:

def register(request, success_url=None,
         form_class=RegistrationForm
         template_name='registration/registration_form.html',
         extra_context=None):

Django Projects (project)

Recommended layout

example.com/
   README
   settings.py
   urls.py
   docs/
       This will hold the documentation for your project
   static/
       -In production this will be the root of your MEDIA_URL
       css/
       js/
       images/
   tests/
       - Project level tests (Each app should also have tests)
   uploads/
       - content imgs, etc
   templates/
       - This area is used to override templates from your reusable apps
       flatpages/
       comments/
       example/
       app1/
       app2/

What is the Django Project?

Django project refers to a settings file, URLs link, simple structure and some Django Apps collection. These things can be written by yourself, also be included in your project within the third party code.

The Project module

Set up

On the   [PROJECT]/settings.py  file

Use relative path

import os
DIRNAME = os.path.dirname(__file__)

MEDIA_ROOT = os.path.join(DIRNAME, 'static')

Setting specific environment related to the use of   local_settings.py  file, and in the   settings.py  the end of the file to import it.

try:
    from local_settings import *
except ImportError:
    pass

URLs

  • In your PROJECT/urls.py file
  • Should contain the logic code at least, in most cases only as a pointer, pointing to your apps own URL configuration.

Deployment

Initialize the Project environment

File system layout

Note

The document file system is heavily skewed towards the Unix style, to use the need to do some additional changes in other operating system.

Virtualenv It is necessary for the Python project. It provides a different method of isolating Python runtime environment. Typical, We at /opt/webapps/<site_name>   production site deployment environment, In the   ~/webapps/<site_name>   directory deploy our development environment site. Each project has its own virtualenv, virtualenv Also serves as the root directory of the project all the relevant code. We use   pip    virtualenv  add the necessary packages.

The boot process looks like this:

cd /opt/webapps
virtualenv mysite.com
cd mysite.com
pip install -E . -r path/to/requirements.txt
source bin/activate

Tip

For convenience, you can in your   virtualenv  create symbolic links Django project root directory. The symbolic link name does not matter, because your project is already on the Python search path. By giving you all the projects play the same symbolic link name, you can use some   bash function and convenient to to save time.

Pack

One of the keys to successful deployment is, Ensure that your development environment to be as close as possible to the deployment of software under the environment of.  software; Pip  provides a simple reproduction method, Let you deploy Python projects in any system can be very consistent. Any third party library app must contain a   requirements.txt    PIP specification file. Projects should be responsible for bringing together all to app specification file, And according to the need to add other specifications.

Your specification file to contain what

Our experience is that, for any application, as long as your operating system not only needs a few default attached. Removed from our specification files in the package is   PIL, database driven and other   pip  cannot be installed packages. These were removed from the specifications on the & nbsp: ref:`project's README <projects-layout>; `  documents to be explained.

The server

Note

Deployment architecture depends largely on the flow of the site. The following description is provided to us, in most cases the best.

Our Linux and PostgreSQL back-end database deployment of Django, based on the   Nginx  process as a front-end proxy, is followed by Apache and mod_wsgi.

Nginx

Nginx Is a very good front-end server, speed, steady as a rock, and resource occupy very little. The following is a typical Nginx site configuration:

What it do?

The first section tells Nginx where to find the Django site hosting server. Second all from   www.domain.com  request is redirected to the domain.com, So that all resources are only a URL can be accessed. The last paragraph bears all work. It tells the Nginx to check the   /var/www/domain.com  the requested file exists. If there is, It returns the file, Otherwise, It put forwards the request to the Django site.

Warning

Yospaly note

The following relates to Apache part are not translated, we strongly recommend the use of Nginx/Lighttpd + SCGI/FastCGI/HTTP, try not to use the complex Apache + mod_wsgi.

SSL

Another benefit to running a frontend server is lightweight SSL proxying. Rather than having two Django instances running for SSL and non-SSL access, we can have Nginx act as the gatekeeper redirecting all requests back to a single non-SSL Apache instance listening on the localhost. Here's what that would look like:

You can include this code at the bottom of your non-SSL configuration file.

Tip

For SSL-aware Django sites like Satchmo, you'll need to "trick" the site into thinking incoming requests are coming in via SSL, but this is simple enough to do with a small addition to the WSGI script we discuss below.

Apache

We run the Apache2 Worker MPM with mod_wsgi in daemon mode. The default settings for the MPM Worker module should be sufficient for most environments although those with a shortage of RAM may want to look into reducing the number of servers spawned. Since Nginx will be listening for HTTP(S) requests, you'll need to bind Apache to a different port. While you're at it, you can tell it to only respond to the localhost. To do so, you'll want to edit the Listen directive

Listen 127.0.0.1:9000

With Apache up and running, you'll need an Apache configuration and WSGI script for each site. A typical Apache configuration for an individual site looks like this:

Tip

In a perfect world, your app would never leak memory and you can leave out the maximum-requests directive. In our experience, setting this to a high number is nice to keep Apache's memory usage in check.

Warning

This will default to a single process with 15 threads. Django is not "officially" thread safe and some external libraries (notably a couple required for django.contrib.gis) are known to not be thread safe. If needed the threads and processes arguments can be adjusted accordingly.

It links to the WSGI script within the project directory. The script is just a few lines of Python to properly setup our environment.

Posted by Christian at November 24, 2013 - 1:44 PM