Django Tips

Some Django tips…


Verify full migrations before creating them (Option -v3 increases verbose to level 3):

python makemigrations -v3 --dry-run

Development Server

Development server won’t automatically restart. After adding the templatetags module, you will need to restart your server before you can use the tags or filters in templates.


Simple for counter loop in a template. Note, the i variable is a string.

{% for i in "1234567" %}
<option value={{ i }}> {{ i }}</option>
{% endfor %}

Comments in templates. First the comment tag, which can be used for single and multiline comments.

{% comment %} this is a comment {% endcomment %}

Second, the single line comment.

{# This is a single line comment #}

Use the template tag with to assign internal template variables

{% with %}
... use geek_id template section ...
{% endwith %}


Signals are synchronous, therefore complexity should be avoided when possible. Add this to

default_app_config = 'assay.apps.WtfAppConfig'

Create for the give app, use this to instantiate app signals

from django.apps import AppConfig
class WtfAppConfig(AppConfig):
 	 name = 'wtf'
 	 verbose_name = 'What the fuck'
 	 def ready(self):
 	  	 import wtf.signals

Add signals to file at the app root (with and friends)

from django.core.signals import request_finished
from django.dispatch import receiver

from .models import FancyNewModel

@receiver(request_finished, sender=FancyNewModel)
def wtf_request_finished_cb(sender, **kwargs):
	print("Request finished!")

request_finished.connect(wtf_request_finished_cb, dispatch_uid="wtf_request_finished")

Template Tags

Create a directory templatetags in your root app directory, create empty so python can recognize the directory. Custom tags can come in the form of simple, or inclusion.

Template Context Processors

When you want something done on a all view scope, it’s probably best done with an template context processor of some sort.

# core/
import socket

def get_host(request):
     return {
         'get_host': socket.gethostname(),

Add the context processor to the settings


Use in templates as needed.

<!-- Host: {{ get_host }} -->

Model Inheritance

How to do basic model inheritance using abstract classes. Most times I keep this code in .mixins.models.

from django.db import models

class SpecialPost(models.Model):
    parent = models.ForeignKey('self', null=True)
    created = models.DateTimeField("Post created", auto_now_add=True)

    class Meta:
        abstract = True

class BlogPost(SpecialPost):
    title = models.CharField(max_length = 256)
    body = models.TextField()

    def __unicode__(self):
        return self.title

Admin Form Fields

class MyModelAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        form = super(MyModelAdmin, self).get_form(request, obj, **kwargs)
        form.base_fields['my_field_name'].initial = 'abcd'
        return form

User Object Access

First make sure you have SessionMiddleware and AuthenticationMiddleware middlewares added to your MIDDLEWARE_CLASSES setting.

The current user is in request object, from a view you can get it by:

def wtf_view(request):
    current_user = request.user

request.user will give you a User object representing the currently logged-in user. If a user isn’t currently logged in, request.user will be set to an instance of AnonymousUser. You can use is_authenticated(), like so:

if request.user.is_authenticated():
    # Do something for authenticated users.
    # Do something for anonymous users

App Management Commands

Just create this simple structure within a Django app. The path management/commands with the necessary python files.

├── management
│   ├── commands
│   │   ├──
│   │   └──
│   └──
... other files

The contents of or your command would look something like the following code snippet. The function handle is the entry point of the command. The variables args and help describe the command.

from import BaseCommand
from .models import Wtf

class Command(BaseCommand):
    args = '<wtf niah ...>'
    help = 'help string'

    def _wtf(self):
        twtf = Wtf(name='Wtf')

    def handle(self, *args, **options):

Admin Site

Not often, but there will be times you want to create a URL to the Django Admin site. Of course you should do this the Django-way by reversing the URL from the view name. For example to get the admin site index URL, use the following.

The admin is the namespace I chose when including the admin site URLs, you might have something different site.

{% url 'admin:index' %}


Creating a form object from a model object

q = Question.object.get(id=Blah)
form = QuestionForm(instance=q)

Now form is a bound form made using q object.


List outdated packages you have installed.

pip list -o

Current list of installed packages

pip freeze

Information about installed package. For example, the package django.

pip show django
No comments
No comments yet.

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>