Django Tips

Some Django tips…

Migrations

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

python manage.py 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.

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 geek_id=geek.id %}
... use geek_id template section ...
{% endwith %}

Signals

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

default_app_config = 'assay.apps.WtfAppConfig'

Create apps.py 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 signals.py file at the app root (with models.py 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 __init__.py 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/context_processors.py
#
import socket

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

Add the context processor to the settings

TEMPLATE_CONTEXT_PROCESSORS =
     'core.context_processors.get_host',
)

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
    print current_user.id

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.
else:
    # 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 __init__.py files.

jscapp
├── management
│   ├── commands
│   │   ├── __init__.py
│   │   └── wtf.py
│   └── __init__.py
├── models.py
... other files

The contents of wtf.py 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 django.core.management.base import BaseCommand
from .models import Wtf

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

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

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

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' %}

Forms

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.

Pip

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>