A Quick Django Tip: User Profiles

I thought I would share with all of you a little trick that I've been using for quite some time in my Django applications. Personally, I find it to be very convenient and simple.

Django allows you to specify an AUTH_PROFILE_MODULE setting if you wish to maintain information about a user beyond the basic username, password, email, etc. To access the profile for a given User instance, you must do something like:

from django.contrib.auth.models import User
user = User.objects.get(pk=1)
user.get_profile().additional_info_field

That seems all find and dandy, right? Just a simple call to get_profile() isn't that difficult. However, if there is not yet an instance of whatever you set AUTH_PROFILE_MODULE to for the user in question, you'll get an error about it when you call get_profile().

My simple-minded way around this is to do something like this:

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    additional_info_field = models.CharField(max_length=50)

User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])

The magic is in the property() and get_or_create. Using the property() feature in Python, means you can just do something like:

from django.contrib.auth.models import User
user = User.objects.get(pk=1)
user.profile.additional_info_field

(with no parentheses after profile) The get_or_create method tells Django to look for any UserProfile objects whose user attribute is the user from which you are accessing the profile property. If no matches are found, an instance of UserProfile is created for you. The lambda function returns the UserProfile instance in both cases.

This trick is very simple. It's also very effective in my experience. I'm sure there are other ways of doing the same thing, but this works for me, and it's just one line of code--no need to even specify the AUTH_PROFILE_MODULE setting! You can apply the same trick to pretty much anything if you'd like. It doesn't have to be just for user profiles. Enjoy!

Django + Aggregation = w00t

One of my good friends has just notified me of some great news in Django land: aggregates are upon us! As of revision 9742, Django includes two new operations: annotate() and aggregate().

Ok, ok, so I haven't actually played with Django's new aggregation functionality yet, but I definitely will!! And I'm sure it will rock.

More information:

GIT-SVN on Slackware 12.2

With all of the hype that git has been receiving lately, I started playing with it a while back to see if it suited me and my wants/needs. I found it to be an interesting utility. I won't go into any details simply because I'm not really all that knowledgeable about all the ins and outs of version control systems, but I will say that I have decided I like it. I'm still not sure whether I prefer GIT over SVN or SVN over GIT.

My problem is that basically all of my projects are based on SVN repositories. I don't want to have to start up a new GIT repository for each of my past projects. Fortunately, there is an interface for GIT to use SVN repositories called git-svn. I use this utility primarily on my EeePC because it saves a good amount of space on my small disk (the git-svn versions of the working copies are typically about half the size of their svn counterparts). Sometimes it's a little wacky, but it works well enough for my needs.

I started using this git-svn utility on a Debian-based distribution. That meant it was insanely simple to get up and running: sudo apt-get install git-svn. I recently installed Slackware 12.2, and I was surprised to find out that the git-svn utility wasn't immediately available to me.

I did some googling to see if others had encountered the same problem. There were several accurate hits, but I couldn't quite find the solution I needed. In the end, I finally got things working. The following information describes what I did to achieve this monumental success.

Trying git svn

The first roadblock that I encountered, obviously, was finding out that git-svn didn't work on my shiny new Slackware installation. After doing a bit of research, I learned that I could substitute the familiar git-svn command with git svn and continue using it as I previously had.

Installing Dependencies

Once I learned about git svn and tried it out, I got a nasty error about Alien/SVN. I've lost track of the original error, and for that I apologize. Doing a little bit of research led me to execute this command as root:

cpan Alien::SVN

I'm not sure exactly whether that step is required, but you might as well do it :).

Next, I downloaded a couple SlackBuilds to create my own Slackware packages suited for my computer.

For each SlackBuild, you must download the original source code along with the actual SlackBuild itself. For example, when retrieving the necessary files for swig, I must download both swig-1.3.35.tar.gz and swig.tar.gz from the link specified. Here are some example commands, which should be run as root:

mkdir -p ~/downloads/slackbuilds; cd ~/downloads/slackbuilds
wget http://slackbuilds.org/slackbuilds/12.2/development/swig.tar.gz
tar zxf swig.tar.gz
cd swig/
wget http://downloads.sourceforge.net/swig/swig-1.3.35.tar.gz
./swig.SlackBuild
installpkg /tmp/swig-1.3.35-i486-1_SBo.tgz

The commands above should create a new directory in /root/ called downloads/slackbuilds. Next, the SlackBuild for swig will be downloaded and extracted, after which the swig source code will be downloaded. The SlackBuild is executed, rendering an installable Slackware package. Finally, the package is installed onto the system.

The process is basically the same for the subversion-bindings SlackBuild. On my system, however, I had to modify the stock SlackBuild slightly. I didn't install Apache on my EeePC because I don't use it and it would just be taking up space. When I tried to execute the SlackBuild for subversion-bindings straight from the archive, it complained about a missing apxs file, which has something to do with Apache.

To avoid the error, I modified the subversion-bindings.SlackBuild script to ignore the apxs thingy. The original ./configure section looked like this:

CFLAGS="$SLKCFLAGS" \
./configure \
  --prefix=/usr \
  --mandir=/usr/man \
  --enable-shared \
  --disable-static \
  --with-apr=/usr \
  --with-apr-util=/usr \
  --with-apxs=/usr/sbin/apxs \
  --with-neon=/usr \
  --with-zlib=/usr \
  --with-pic \
  --with-ssl \
  --build=$ARCH-slackware-linux

I just removed the line that says --with-apxs=/usr/sbin/apxs \ and ran the SlackBuild script again. Worked like a charm.

At this point everything appeared to be able to work properly. Running git svn from the command line no longer spit out that nasty error I mentioned earlier. Instead it gave me the options I would expect to see.

That's when I tried to update an existing working copy of an SVN repository. It gave me this error:

$ git svn rebase
Authentication realm: <http://special.domain.com:80> Subversion - code
Password for 'myuser': Can't locate Term/ReadKey.pm in @INC (@INC contains:
/usr/lib/perl5/site_perl/5.10.0/i486-linux-thread-multi /usr/lib/perl5
/site_perl/5.10.0 /usr/lib/perl5/5.10.0/i486-linux-thread-multi /usr/lib
/perl5/5.10.0 /usr/lib/perl5/site_perl /usr/lib/perl5/vendor_perl/5.10.0
/i486-linux-thread-multi /usr/lib/perl5/vendor_perl/5.10.0 /usr/lib/perl5
/vendor_perl .) at /usr/libexec/git-core/git-svn line 3071.

That's not very nice, now is it? The solution was fairly simple: install Perl's Term::ReadKey module. As root, execute the following command:

cpan Term::ReadKey

After doing that I was able to happily update my working copy and move on.

I don't envision that this article will be the all-knowing, all-powerful resource for how to use git-svn on Slackware, but I sure hope it will help some other folks who run into the same problems as me.

Syntax Highlighting, ReST, Pygments, and Django

Some of you regulars out there may have noticed an interesting change in the presentation of some of my articles: source code highlighting. I've been interested in doing this for quite some time, I just never really got around to implementing it until last night.

I found this implementation process to be a bit more complicatd than I had anticipated. For my own benefit as well as for anyone else who wants to do the same thing, I thought I'd document my findings in a thorough article for how to add syntax highlighting to an existing Django- and reStructuredText-powered Web site.

The power behind the syntax highlighting is:

Python is a huge player in this feature because reStructuredText (ReST) was built for Python, Pygments is the source highlighter (written in Python), and Django is written in Python (and my site is powered by Django). Some of you may recall that I converted all of my articles to ReST not too long ago because it suited my needs better than Textile, my previous markup processor. At the time, I was not aware that the conversion to ReST would make it all the easier for me to implement the syntax highlighting, but last night I figured out that that conversion probably saved me a lot of frustration. Cascading Stylesheets (CSS) are responsible for making the source code actually look good, while Pygments takes care of assigning classes to various parts of the designated source code and generating the CSS.

So, the first set of requirements, which I will not document in this article, are that you already have a Django site up and running and that you're familiar with ReST syntax. If you have the django.contrib.flatpages application installed already, you can type up some ReST documents there and apply the concepts discussed in this article.

Next, you should ensure that you have Pygments installed. There are a variety of ways to install this. Perhaps the easiest and most platform-independent method is to use easy_install:

$ easy_install pygments

This command should work essentially the same on Windows, Linux, and Macintosh computers. If you don't have it installed, you can get it from its website. If you're using a Debian-based distribution of Linux, such as Ubuntu, you could do something like this:

$ sudo apt-get install python-pygments

...and it should take care of downloading and installing Pygments. Alternatively, you can download it straight from the PyPI page and install it manually.

Now we need to install the Pygments ReST directive. A ReST directive is basically like a special command to the ReST processor. I think this part was the most difficult aspect of the implementation, simply because I didn't know where to find the Pygments directive or how to write my own. Eventually, I ended up downloading the Pygments-1.0.tar.gz file from PyPI, opening the Pygments-1.0/external/rst-directive.py file from the archive, and copying the stuff in there into a new file within my site.

For my own purposes, I made some small adjustments to the directive over what come with the Pygments distribution. I think it would save us all a lot of hassle if I just copied and pasted the directive, as I currently have it, so you can see it first-hand.

"""
    The Pygments reStructuredText directive
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    This fragment is a Docutils_ 0.4 directive that renders source code
    (to HTML only, currently) via Pygments.

    To use it, adjust the options below and copy the code into a module
    that you import on initialization.  The code then automatically
    registers a ``code-block`` directive that you can use instead of
    normal code blocks like this::

    .. code:: python

            My code goes here.

    If you want to have different code styles, e.g. one with line numbers
    and one without, add formatters with their names in the VARIANTS dict
    below.  You can invoke them instead of the DEFAULT one by using a
    directive option::

    .. code:: python
       :number-lines:

            My code goes here.

    Look at the `directive documentation`_ to get all the gory details.

    .. _Docutils: http://docutils.sf.net/
    .. _directive documentation:
       http://docutils.sourceforge.net/docs/howto/rst-directives.html

    :copyright: 2007 by Georg Brandl.
    :license: BSD, see LICENSE for more details.
"""

# Options
# ~~~~~~~

# Set to True if you want inline CSS styles instead of classes
INLINESTYLES = False

from pygments.formatters import HtmlFormatter

# The default formatter
DEFAULT = HtmlFormatter(noclasses=INLINESTYLES)

# Add name -> formatter pairs for every variant you want to use
VARIANTS = {
    'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True),
}


from docutils import nodes
from docutils.parsers.rst import directives

from pygments import highlight
from pygments.lexers import get_lexer_by_name, TextLexer

def pygments_directive(name, arguments, options, content, lineno,
                       content_offset, block_text, state, state_machine):
    try:
        lexer = get_lexer_by_name(arguments[0])
    except ValueError:
        # no lexer found - use the text one instead of an exception
        lexer = TextLexer()
    # take an arbitrary option if more than one is given
    formatter = options and VARIANTS[options.keys()[0]] or DEFAULT
    parsed = highlight(u'\n'.join(content), lexer, formatter)
    parsed = '<div class="codeblock">%s</div>' % parsed
    return [nodes.raw('', parsed, format='html')]

pygments_directive.arguments = (1, 0, 1)
pygments_directive.content = 1
pygments_directive.options = dict([(key, directives.flag) for key in VARIANTS])

directives.register_directive('code-block', pygments_directive)

I won't explain what that code means, because, quite frankly, I'm still a little hazy on the inner workings of ReST directives myself. Suffice it to say that this snippet allows you to easily highlight blocks of code on ReST-powered pages.

The question now is: where do I put this snippet? As far as I'm aware, this code can be located anywhere so long as it is loaded at one point or another before you start your ReST processing. For the sake of simplicity, I just stuffed it in the __init__.py file of my Django site. This is the __init__.py file that lives in the same directory as manage.py and settings.py. Putting it in that file just makes sure it's loaded each time you start your Django site.

To make Pygments highlight a block of code, all you need to do is something like this:

.. code:: python

    print 'Hello world!'

...which would look like...

print 'Hello world!'

If you have a longer block of code and would like line numbers, use the :number-lines: option:

.. code:: python
    :number-lines:

    for i in range(100):
        print i

...which should look like this...

for i in range(100):
    print i

That's all fine and dandy, but it probably doesn't look like the code is highlighted at all just yet (on your site, not mine). It's just been marked up by Pygments to have some pretty CSS styles applied to it. But how do you know which styles mean what?

Luckily enough, Pygments takes care of generating the CSS files for you as well. There are several attractive styles that come with Pygments. I would recommend going to the Pygments demo to see which one suits you best. You can also roll your own styles, but I haven't braved that yet so I'll leave that for another day.

Once you choose a style (I chose native for Code Koala), you can run the following commands:

$ pygmentize -S native -f html > native.css
$ cp native.css /path/to/site/media/css

(obviously, you'd want to replace native with the name of the style you like the most) Finally, add a line to your HTML templates to load the newly created CSS file. In my case, it's something like this:

<link rel="stylesheet" type="text/css" href="/static/styles/native.css" />

Now you should be able to see nicely-formatted source code on your Web pages (assuming you've already got ReST processing your content).

If you haven't been using ReST to generate nicely-formatted pages, you should make sure a couple of things are in place. First, you must have the django.contrib.markup application installed. Second, your templates should be setup to process ReST markup into HTML. Here's a sample templates/flatpages/default.html:

{% extends 'base.html' %}
{% load markup %}

{% block title %}{{ flatpage.title }}{% endblock %}

{% block content %}
<h2>{{ flatpage.title }}</h2>

{{ flatpage.content|restructuredtext }}
{% endblock %}

So that short template should allow you to use ReST markup for your flatpages, and it should also take care of the magic behind the .. code:: python directive.

I should also note that Pygments can handle a TON of languages. Check out the Pygments demo for a list of languages it knows how to highlight.

I think that about does it. Hopefully this article will help some other poor chap who is currently in the same situation as I was last night, and hopefully it will save you a lot more time than it took me to figure out all this junk. If it looks like I've missed something, or maybe that something needs further clarification, please comment and I'll see what I can do.

Announcing django-axes 0.1.1-rc1

I've released a new version of django-axes this morning. This project allows you to keep track of failed login attempts on your Django-powered sites quickly and easily. It pays attention to the built-in login functions for the Django administration utility as well as the stock django.contrib.auth.views.login method. If a particular user fails to login successfully after 3 tries (this number is customizable), a record is made of the failure for the site admins to review.

This new version addresses what appeared to be related to some recursive function calls interpretting one failed login attempt as much more than that (sometimes more than 100 alleged failed login attempts for a single actual failed login attempt!). I also added a log file for easier access to the stuff that happens when django-axes kicks into action.

For more information, see the following links:

Please comment with any questions, suggestions, etc you have in regards to django-axes!

django-watermark 0.1.5-pre1

I've been making several updates to django-watermark during my more boring classes the past couple days. I have just released a new version for your pleasure.

Changes include:

  • A lot of code refactoring. There was a lot of logic in the watermark filter itself. I decided this logic should be placed elsewhere so as to make the utils.watermark function easier to use outside the realm of the watermark filter.
  • Removed the "parameter precedence" that used to exist between the positioning, tiling, and scaling parameters. Previously, if scale was defined, any values for position and tile were ignored. Similarly, if any value was given for tile, any value for position was ignored. Now you can use all three parameters simultaneously.
  • Added a couple of goodies for positioning and scaling.

I think this is quite a stable release. Please notify me if you find any problems with it!!

django-watermark 0.1.2-pre1

I've added a few updates to django-watermark and figured it was time to announce another release. Updates include:

  • the ability to place watermarks randomly on the target image
  • updated the way relative positioning works. Now, position=50%x50% will center the watermark image on the target image. Previously django-watermark placed the top-left corner of the watermark image in the center of the target image.
  • the ability to convert the watermark image to a transparent greyscale image before applying it to the target image
  • the ability to rotate the watermark image using either a specific number of degrees or usign a random rotation value

Both Google Code and PyPI have been updated with these changes.

Project Release: django-reploc 0.1.0-pre1

Here's yet another application to help you make your site more useful to your users. django-reploc is a "representative locator" for Django-powered Web sites. It uses the Google Maps API to offer your users an interactive map of your representatives, vendors, friends, houses, etc.

I built this application to be a dealer locator for one of my clients. The application provides a way for you to create "representatives," and each representative may have one or more locations. For example, say you are a producer of clothing and apparel, ranging from shoes to pants to t-shirts to sweaters to hats to bags and so on. Perhaps your bigger representatives (or vendors) carry your products in all of their retail branches. reploc gives you a way to display each of these locations for the one vendor on a map for your users.

In addition to that, while the bigger vendors might carry your products in all locations, perhaps some locations only carry particular lines of your products. For example, a vendor location in Miami, Florida might carry a good deal of your sandals and none of your sweatshirts, while a vendor location in Bangor, Maine might not bother with any sandals but keeps sweatshirts in stock year-round. reploc offers a way for you to describe which product lines each location carries by the use of "attributes".

However, it can be used for much more than just that. Pretty much any location that you can show on Google Maps (is there anything that can't be shown on Google Maps anymore?) can be displayed with this application.

Furthermore, you can search for locations within a certain radius of an address that your users specify! A nice circle is drawn on the map, making it visually easier to understand what is and isn't within range. To make things even easier, the locations that do not fall within the radius of the given address are hidden from the map.

Finally, once a user finds a location within the radius of the address they specify, they are able to get driving directions to help them get right where they need to go!

w00t!

To learn more, go to the project page: http://code.google.com/p/django-reploc/

Setup a favicon.ico in Django

Up until a couple weeks ago, I had never installed a FavIcon on any of my Django sites. I never really thought about it until one day I enabled the SEND_BROKEN_LINK_EMAILS setting for one of my sites. As soon as I did that, I was able to track down links to broken pages very quickly. It also notified me that I didn't have a favicon.ico file setup anywhere on my site, and there are a great many programs out there that look for this file automatically.

At first I tried to go through Apache to get this working, but I'm no Apache guru so I was less than successful in taking this route. A couple of days ago I figured out a little trick to make the missing favicon.ico file stop sending me "broken link" e-mails hundreds of times a day. The solution? Put a favicon on my site, of course!

The approach I took was to simple add some information to my main urls.py file. Here's the line straight from my URLconf:

(r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': '/static/images/favicon.ico'}),

Hah! Simple isn't it? This way Apache is still handling the actual serving of the static image file--Django just handles the redirect. Ever since I added this line to my URLconf, I've not received one "broken link" e-mail pertaining to the missing favicon.ico file. That leads me to believe that most applications can understand the redirect and plug the actual image file where it belongs.

Oh, and for those of you who might be curious... My favicon.ico is actually just a PNG image that I renamed to favicon.ico. Again, most things seem to understand this (but I could be wrong).

See below for a more complete example of my URLconf

from django.conf.urls.defaults import *

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^admin/(.*)', admin.site.root),
    (r'^robots\.txt$', 'django.views.generic.simple.direct_to_template', {'template': 'robots.txt', 'mimetype': 'text/plain'}),
    (r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': '/static/images/favicon.ico'}),
    (r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'base_home.html'}),
)

Project Release: django-axes 0.1-pre

Ever curious to see information about failed login attempts on your site? This morning I threw together a small, simple Django application that allows you to do just that. I'm calling this project django-axes, which is pronounced as "jango access".

I've only tested it on my own site, so it must still undergo some more in-depth testing before I can call it a stable application. From my testing, however, it works exactly as I expect it to.

For more information, check out the project homepage on Google Code.