Let’s Be Lazy-Productive: Class-Based Generic Views

Last modified: May 25, 2016 | Posted in Django Tutorials

We, programmers, are lazy. We despise repetitive tasks and are bored by monotonous project requirements. As much as possible, we automate processes and use abstractions for patterns that we always use in our work. And yet, despite being lazy, we also want to be efficient and productive. Can we really be lazy and efficient and productive, all at the same time?

Since Django 1.3, generic views for Django were implemented using classes instead of functions. With these new class-based generic views, writing view code is easier, faster and more organized. In addition to that, we benefit from having a cleaner, more reusable, and more structured code base. We used to write function-based views like this one:

from django.shortcuts import render_to_response
from django.template import RequestContext

def simple_view(request):
    """ This view just displays a template with some context. """

    context = {'a': 1, 'b': 2}

    return render_to_response('simple_template.html', context=RequestContext(request, context))

For views that really do something, we might have ended up writing the following:

from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render_to_response
from django.templates import RequestContext
from django.views.decorators.csrf import csrf_protect
from .forms import MyObjectModelForm
from .models import MyObject

def single_object_view(request, object_pk):
    This view displays the details of an object on GET and
    allows logged-in users to edit the object on POST.


    object = get_object_or_404(MyObject, object_pk)
    form = None

    if request.method == 'GET':
        # we just display the details for the object and an edit form

        form = MyObjectModelForm(instance=object)
    elif request.method == 'POST':
        # process object update

        form = MyObjectModelForm(instance=object, data=request.POST, files=request.FILES)
        if form.is_valid():
            object = form.save()
            form = MyObjectModelForm(instance=object)

    context = {'object': object, 'form': form}

    # additional stuff could go here

    return render_to_response('single_object.html', context=RequestContext(request, context))


Awesome forms with django-crispy-forms

Last modified: May 25, 2016 | Posted in Django Tutorials

Django-crispy-forms is a third-party Django application which lets you create beautiful forms in “a very elegant and DRY way”. Best of all—you don’t need to code form templates unless you really want to.

The resulting form markup, by default, is compatible with Twitter Bootstrap 2. If you want to use Bootstrap 3 to render your forms, add the following setting to your settings.py:


To give a brief demonstration of what `django-crispy-forms` can do, let us try creating a user profile form in Django.

We begin with a simple user model:

class User(AbstractUser):
    COUNTRIES = ()   # Contents are left as an exercise to the reader

    # Address
    address1 = models.CharField(max_length=50)
    address2 = models.CharField(max_length=50)
    city = models.CharField(max_length=50)
    state = models.CharField(max_length=50)
    country = models.CharField(max_length=50, choices=COUNTRIES)

    # Contact
    mobile = models.CharField(max_length=32)
    home = models.CharField(max_length=32)
    office = models.CharField(max_lenghth=32)
    twitter = models.CharField(max_length=100)

    def __unicode__(self):
        return self.username

This example works with custom user models available since Django 1.5. (more…)

Tmux is a terminal multiplexer

Last modified: May 25, 2016 | Posted in Django Tutorials

When I started in web development, Gnome terminal and its tab interface were the tools I used for my terminal needs. We can say that web development and the terminal go hand in hand. As I progressed with web development I started using Guake, a top-down terminal that gives me a quick access to a terminal while pressing just one key. Sadly though, tab interfaces on terminal windows pale in comparison to its modern browser counterparts. Ugly! Also, although I have naturally grasped the keyboard shortcuts for adding, removing and switching tabs, it still felt like it has held me back since most of the time I would just need to view the debug output of some process (i.e. Django development server). The time consumed switching between the open tabs is not acceptable.

So as I scoured the web for a solution and I encountered the term “terminal multiplexer”, which can be thought of as a graphical window manager for terminal sessions. So yeah, the next thing that came up was screen, which I was kind of familiar with, as I have used it maintain my session on remote servers. But it was the first time that I really found out you can maintain multiple windows (or tabs) within a screen session and you can also split a window into multiple panes. But there was one specific feature lacking on screen at the time: vertical splitting. Enter tmux. Other than the vertical splitting (which is now available in screen btw), tmux is easier to use for multi-user and multi-sessions, which makes it an even better fit for remote pair programming.

My ~/.tmux.conf.

# remap prefix to Control + a
unbind C-b
set-option -g prefix C-a

#Automatically set window title
set-window-option -g automatic-rename on
set-option -g set-titles on

# Assign new shortcut keys for spliting window vertically and horizontally
bind-key v split-window -h
bind-key s split-window -v

# Navigate CTRL-arrow keys to switch panes
bind -n C-Left select-pane -L
bind -n C-Right select-pane -R
bind -n C-Up select-pane -U
bind -n C-Down select-pane -D

#Shift+arow keys to switch windows
bind -n S-Left previous-window
bind -n S-Right next-window
# force a reload of the config file
unbind r
bind r source-file ~/.tmux.conf

# quick pane cycling
unbind ^A
bind ^A select-pane -t :.+


Top Three Insights Why You Should Use Django

Last modified: May 25, 2016 | Posted in Django Tutorials

There are many options out there for a new project; they come in the form of languages, frameworks, concepts and paradigms. While many of them are good, our experience with over 50,000 development hours has shown us that Django is better.

In a finished product, Django will return a better, faster, more stable and more sustainable result than what many other options can achieve.

We firmly believe that this is the best option for development, and that it is the best option for your project. Below you’ll find our top three reasons why we use Python and why you should, too!

1) Reliability

The strongest reason to use Django for the development of your web application is due to stability and reliability. Django is built on top of the Python programming language, which is renown for its power, simplicity and general readability.

The Python language has been in active development for many years and gains the benefit of countless hours of community involvement. Python’s stability stems from the fact that it has been alive and kicking since 1991; being around for two decades and counting has given it the time to become stable, compared to many recent languages.

New technologies invariably come with bugs, glitches, memory leaks, and other limiting factors, but Python’s vast user group has had the time to iron these out, resulting in an incredibly stable and reliable product.

On top of that, the Python community is very active in the development and continuation of the language. These factors combine to make Python extremely feature rich and on the cutting edge of new technologies. And, despite the length of time Python has been around, developers continue to maintain a high level of standard practices.

Moreover, Django leverages the power of Python and enables it to serve your dynamic content quickly, reliably, and accurately.

2) Flexibility

Many languages used for web development today exist only for that purpose and serve no other function.

This isn’t inherently a bad thing, however it does limit the scope of your production options. (more…)

Three Fast and Fun Projects for New Django Developers

Last modified: May 25, 2016 | Posted in Django Tutorials

Django is a sophisticated web platform that uses Python and supports streamlined design and rapid development.

Django is also an excellent foundation upon which to build other web-oriented skills, and perhaps best of all, it is simply a lot of fun to use it to create functioning web objects.

In that spirit, we present three projects that Django developers can learn and grow from and have a blast while doing it.

1. Django Haystack

Haystack is a BSD-licensed modular search component and an excellent learning opportunity for any Django developer.

The goal of Haystack is to be a plug-and-play search module for any Django app. A defining feature of Haystack is its familiar and unified API, and that standardization makes it accessible to the newcomer and a powerful Django learning tool in general.

What makes Haystack so popular among Django users is that you only ever need to write search code for a particular app once, which is the way search should be.

With that code in hand, users can simply plug in any one of the number of search backends, such as Elastisearch, Solr, Whoosh and Xapian.

Django Haystack — https://github.com/toastdriven/django-haystack