Django project: from beginning to working server

In this post i'll describe my experience of deploying django project to VPS-hosting.

Steps of deploying and server setup:

  1. Creation of django project
  2. Deploy setup
  3. Server setup
  4. Deploy

Creation of django project

Assume, that project is called myproject.

First, create it on local machine. We'll need pip and virtualenv (if not installed yet).

Create virtual environment:

virtualenv venv-myproject

Acitvate it:

# on *nix system
source venv-myproject/bin/activate

REM on windows
venv\Scripts\activate ...

Posted on 2013-11-13

Django logging settings

Let's look at default django logging settings and try to make them more useful.

Here what we have in after command startproject project_name (django 1.5):

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See for
# more details on how ...

Posted on 2013-09-26

Python logging for every day

When writing a small python program or script, it is sometimes needed to output debug message or maybe event. It is known, that python has logging module exactly for that purpose. But in my case usually such thing happens: it is lack of time and hands just writes print instead of logging, because i can't remember all those complicated logging settings. But then, if script is launched often or i must provide it ...

Posted on 2013-08-20

Django queryset.count cache

Django queryset.count cache

Once i mentioned, that my django application makes several similiar queries like 'SELECT COUNT(*) ...'. As it turns out (for me it was surprise), queryset.count() has not obvious cache. But let me start the story from the beginning (and sorry for my english :) ).

As it is known, django's queryset is lazy and have cache.

Lets say we have such model:

class Item(models.Model):
    name = models.CharField(max_length=50)

When some django query is ...

Posted on 2013-07-11

Unicode string formatting

Did you know, if one of values in string formatting expression with % operator is unicode, then result string will also be unicode?

>>> "Hello, %s" % u"Alex"
u'Hello, Alex'
>>> "Hello, %s" % u"Алексей"
u'Hello, \u0410\u043b\u0435\u043a\u0441\u0435\u0439'

I used to work with .format string method and its behavior is more attractive to me: type of source string is saved and if some parameter contains non-ascii symbols, UnicodeEncodeError exception is raised ...

Posted on 2013-06-20

Parse url which contains unicode query, using urlparse.parse_qs

Task: get dictionary of URL GET query. For example, we have following url:

it is needed to get a dict:

{'key': ['value'], 'a': ['b']}

Values are lists, because one key may have several values:

Out: {'key': ['value'], 'a': ['b', 'c']}

In python there is a function urlparse.parse_qs for that purpose:

>>> import urlparse
>>> query = "key=value&a=b ...

Posted on 2013-05-22

Django admin site optimisation

Django admin site optimisation

It is known, that less amount of database attempts leads to better performance. Usually admin page - part of site with low traffic, but anyway it is good, if no additional database calls happen there. It is more pleasant to use it, because page renders faster and also frees server resources.

In this post i'll try to reduce some database attempts in admin page, when model method __unicode__ contains related object field. I suppose, that ...

Posted on 2013-04-12

Python function with mutable default arguments

Python mutable default arguments

In python default function arguments are created during executing instruction def and not at each function call. If argument value is immutable object (for example string, integer, tuple) it is ok, but if value is mutable, then there can be a trap:

    def foo(l=[]):
        return l

It seems, that every call to foo() will return list ['x']. But:

    >>> foo()
    >>> foo()
    ['x', 'x']
    >>> foo()
    ['x', 'x', 'x']

So, if it is ...

Posted on 2013-03-06

Multilanguage site on django without redirects

Starting from django 1.4, it is possible to set url prefix for each activated language. For example, we want site, that will have russian and english version.

To do it, add following to

    # default language, it will be used, if django can't recognize user's language
    LANGUAGE_CODE = 'ru'

    # list of activated languages
        ('ru', 'Russian'),
        ('en', 'English'),

    # enable django’s translation system
    USE_I18N = True

    # specify path for translation files
        os ...

Posted on 2013-02-26

Script for downloading music from vkontakte

Vkontakte audio download

A quick search of corresponding python script doesn't give results. In post on habra link is broken. So i decided to write my own bicycle, it is avaliable here.

Launch (needs installed python interpreter):


Tested on python 2.6 and 2.7. No external libraries required.


Script checks saved access_token. If it doesn't exists or expired, then page with authorisation is opened in browser. After confirmation you will ...

Posted on 2013-02-04

Sublime text and github gists

Sublime text and github gist

In Sublime text there are big variety of useful tools, that help to write code. I've learned only a small part of them, currently i'm trying to write in Vintage mode (vim style cursor management). But now i want to tell about integration github gists with sublime text. If you don't now, github gists let you save snippets as a separate file without creation full repository. But it have many repository features ...

Posted on 2013-01-03

MobileESP: Easily detect mobile web site visitors

Script will be useful, if you want to show different version of site for desktop computers and mobile devices. Big variety of methods to detect mobile type. Avaliable in different languages, including python. The port to python was made by me with help from my freelance customer.

Here how it can be used in django project:

from mobileesp import mdetect

user_agent = request.META.get("HTTP_USER_AGENT")
http_accept = request.META.get("HTTP_ACCEPT")
if user_agent and http_accept:
    agent ...

Posted on 2012-11-29

Debug django project with embedded python debugger pdb

I use sublime-text as code editor. It doesn't have a debugger, so to debug django projects i often used

print var_name

and look for output in local development server console. I use this approach today also, but sometimes it is great to run code step by step to see variables at each step.

It can be done with embedded python debugger pdb:

import pdb; pdb.set_trace()

I.e. we put this line in needed ...

Posted on 2012-11-18

Cloud service Openshift

Openshift logo

I know a few hosting providers with free account and python availability. It is Google App Engine and Alwaysdata. But recently i found great project Openshift from RedHat and this blog site is working on it. Let me describe mentioned hostings first.

Google app engine

The main trouble of google app engine - limited amount of python libraries. Of course, you can use pure python libs, but you can't setup libs that requires C compilation ...

Posted on 2012-10-08

Aphorism messenger

Aphorism messenger

I have an interesting project i want to tell you about. The idea to create it was born when i was learning Java. I have read couple of books, made some small task programs but i would like to create something bigger.

Project summary:

Desktop program (client), that lives in a tray and periodically shows aphorisms. It takes aphorisms from web-service (server), so data base with aphorisms lives in one place and it doesn't ...

Posted on 2012-08-31

This site


Often reading other blogs i had a wish to start my own, but i just can't find time for it. Also i was wondering, what will i write ...

Posted on 2012-08-28