Django Snippets

Django commands

Django version

>>> import Django
>>> print django.version

Changing the Address and the Port

python manage.py runserver ip_address:port_number

Source files

Import

Don’t put project name in the imports. Instead of using

from project3.xyz.models import Author

you can use

from xyz.models import Author

You can write the above statement as the django project is there on the python path.

Templates

Don’t hard code static files in your templates

When you want to link static files like (java script files,css files,images) don’t do the below

(Assuming that MEDIA_URL is “/appmedia/” )

<link rel="stylesheet" type="text/css" href="/appmedia/wysiwyg/jHtmlArea.css" />
<script type="text/javascript" src="/appmedia/wysiwyg/jHtmlArea.js"></script>
<script type="text/javascript" src="/appmedia/scripts/editor.js"></script>
<script type="text/javascript" src="/appmedia/scripts/comments.js"></script>
<script type="text/javascript" src="/appmedia/scripts/voting.js"></script>

The problem with above approach that you will need to rewrite these files if you change the static content directory.

It's better to use the context variable MEDIA_URL instead of hard coding as “/appmedia/” as below:

<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}wysiwyg/jHtmlArea.css" />
<script type="text/javascript" src="{{ MEDIA_URL }}wysiwyg/jHtmlArea.js"></script>
<script type="text/javascript" src="{{ MEDIA_URL }}scripts/editor.js"></script>
<script type="text/javascript" src="{{ MEDIA_URL }}scripts/comments.js"></script>
<script type="text/javascript" src="{{ MEDIA_URL }}scripts/voting.js"></script>

Load template tags belonging to third party apps only once

Before using the template tags in a template from third party apps we need to do

{% load template_tags %}

To avoid doing the above for every template you can do the following:

from django import template
template.add_to_builtins('project.app.templatetags.custom_tag_module')

Just put the above code in any file which automatically loads at the start like (settings.py,urls.py,every app models.py).

The above code loads the template tags at the start and you can use the template tags in any templates without using the code {% load template_tags %}

settings.py

Directory parameters

In settings.py don’t write MEDIA_ROOT and TEMPLATE_DIRS as below

TEMPLATE_DIRS = "/home/html/project/templates"
MEDIA_ROOT = "/home/html/project/appmedia/"

The above will cause problem when you move your project to deployment servers (changing from one server to another server) , changing from one OS to another OS as you need to take of proper directory structure.

You can use the following:

SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(SITE_ROOT, 'appmedia')
TEMPLATE_DIRS = ( os.path.join(SITE_ROOT, 'templates'),)

urls.py

Reusing an app

Don’t write all yours urls in project/urls.py. Instead segregate across multiple apps. This helps to reuse the app for a different project without doing tedious modifications.

Streamlining Function Imports

Instead of

from django.conf.urls.defaults import *
from mysite.views import hello, current_datetime, hours_ahead
 
urlpatterns = patterns('',
    (r'^hello/$', hello),
    (r'^time/$', current_datetime),
    (r'^time/plus/(\d{1,2})/$', hours_ahead),
)

You can import the views module itself.

from django.conf.urls.defaults import *
from mysite import views
 
urlpatterns = patterns('',
    (r'^hello/$', views.hello),
    (r'^time/$', views.current_datetime),
    (r'^time/plus/(d{1,2})/$', views.hours_ahead),
)

Another way is to pass a string containing the module name and function name rather than the function object itself.

from django.conf.urls.defaults import *
 
urlpatterns = patterns('',
    (r'^hello/$', 'mysite.views.hello'),
    (r'^time/$', 'mysite.views.current_datetime'),
    (r'^time/plus/(d{1,2})/$', 'mysite.views.hours_ahead'),
)

We can factor out that common prefix and have a shorter version

from django.conf.urls.defaults import *
 
urlpatterns = patterns('mysite.views',
    (r'^hello/$', 'hello'),
    (r'^time/$', 'current_datetime'),
    (r'^time/plus/(d{1,2})/$', 'hours_ahead'),
)

Special-Casing URLs in Debug Mode

To alter your URLconf’s behavior while in Django’s debug mode

from django.conf import settings
from django.conf.urls.defaults import *
from mysite import views
 
urlpatterns = patterns('',
    (r'^$', views.homepage),
    (r'^(\d{4})/([a-z]{3})/$', views.archive_month),
)
 
if settings.DEBUG:
    urlpatterns += patterns('',
        (r'^debuginfo/$', views.debug),
    )

Information About the URL

Always use these attributes/methods instead of hard-coding URLs in your views. This makes for more flexible code that can be reused in other places.

Attribute/method Description Example
request.path The full path, not including the domain but including the leading slash. "/hello/"
request.get_host() The host (i.e., the “domain,” in common parlance) "www.example.com"
request.get_full_path() The path, plus a query string (if available). "/hello/?print=true"
request.is_secure() True if the request was made via HTTPS. Otherwise, False. True or False
# BAD!
def current_url_view_bad(request):
    return HttpResponse("Welcome to the page at /current/")
 
# GOOD
def current_url_view_good(request):
    return HttpResponse("Welcome to the page at %s" % request.path)

Admin

filter_horizontal

Use filter_horizontal or filter_vertical for any ManyToManyField . It’s far easier to use than a simple multiple-select widget.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.