Welcome to Django-useful’s documentation!¶

Django-useful is a collection of reusable Django snippets.

Unlike other similar packages, I’ll try to keep it fully tested, documented, and compatible with several Django and Python versions.

Work in progress: Currently this package is still under development, and intended mainly for my personal use. New features will be added gradually.

Compatible with:

  • Python: 2.6, 2.7
  • Django: 1.3, 1.4
  • Celery: 2.5, 3.0 (optional)

Contents¶

Installation¶

Install by using pip or easy_install:

pip install django-useful

Or install from source:

git clone git@github.com:yprez/django-useful.git
cd django-useful
python setup.py install

To add this application into your project, just add it to your INSTALLED_APPS setting:

INSTALLED_APPS = (
    ...
    'useful',
)

Usage¶

Helpers¶

get_object_or_none¶

useful.helpers.get_object_or_none(model, *args, **kwargs)¶

Like get_object_or_404, but doesn’t throw an exception.

Allows querying for an object that might not exist without triggering an exception.

Sample usage:

from django.contrib.auth.models import User
from useful.helpers import get_object_or_none

user = get_object_or_none(User, username='test')

if not user:
    pass  # ... do something

While withouth the shortcut you would do something like:

try:
    user = User.objects.get(username='test')
except User.does_not_exist:
    user = None

This also simplifying more advanced cases:

user = get_object_or_none(SomeModel, field='value1') \
        or get_object_or_none(SomeModel, field='value2')

json_response¶

useful.helpers.json_response(data, status=200, serializer=None)¶

Returns an HttpResponse object containing JSON serialized data.

The mime-type is set to application/json, and the charset to UTF-8.

Sample usage:

# views.py
from useful.helpers import json_response

def some_view(request):
    data = {'a': 'b', 'key': 'value'}

    return json_response(data)  # Returns an HttpResponse object
                                # With `data` encoded as json.

Return a different status code:

# views.py
from useful.helpers import json_response

def some_view(request):
    return json_response(data={
        'status': 'error',
        'message': 'something terrible happened!',
    }, status=500)

Or use a custom JSON serializer:

# views.py
import datetime
from useful.helpers import json_response

def some_view(request):
    data = {'date': datetime.datetime.now()}

    dthandler = lambda x: (x.isoformat()
                           if isinstance(x, datetime.datetime) else x)

    return json_response(data, serializer=dthandler)

jsonp_response¶

useful.helpers.jsonp_response(data, callback='f', status=200, serializer=None)¶

Returns an HttpResponse object containing JSON serialized data, wrapped in a JSONP callback.

The mime-type is set to application/x-javascript, and the charset to UTF-8.

Usage is the same as json_response

Views¶

ExtraContextTemplateView¶

Sample usage:

# urls.py

from useful.views import ExtraContextTemplateView

urlpatterns = patterns('',
    # ...
    url(r'^sample_extra_context_view$',
        ExtraContextTemplateView.as_view(template_name='sample.html',
                                         extra_context={'extra': 'context'}),
        name='sample_extra_context_view'),
)

Context Processors¶

settings (context processor)¶

useful.context_processors.settings(request)¶

Settings context processor Allows access to project settings from the templates

Sample usage

Enable it in settings.py:

# settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
    # ...
    'useful.context_processors.settings',
)

Then access {{ settings }} in the template, for example:

{{ settings.SITE_NAME }}

Or:

{% if settings.DEBUG %}<h1>Debug!</h1>{% endif %}

Tasks¶

Common Celery tasks.

call_management_command¶

This task is useful for converting periodic tasks in the form of Django management being run as cron jobs to Celery periodic tasks run with celerybeat.

Sample usage:

# settings.py
from datetime import timedelta

CELERYBEAT_SCHEDULE = {
    'cleanup': {
        'task': 'call_management_command',
        'schedule': timedelta(hours=1),
        'args': ('cleanup', ),
    },
}

Indices and tables¶