Archive for the 'Django' Category

Changing the Django Admin site title

Saturday, April 3rd, 2010

Often the Django Admin should look a little different for the sake of your users or for the sake of yourself (running multiple django sites with identical looks and titles can be such a pain). Often users don’t know what Django is, and it takes ages to explain, and even after that they have no clue. Also, often my administration has nothing to do with a website, so I don’t want the text “Site administration”.

First of all, you wanna add templates/admin/base_site.html to your project. This file can safely be overwritten, since it’s a file that the django devs have intended for the exact purpose of customizing your admin site a bit. Here’s an example of what to put in the file:

{% extends "admin/base.html" %}
{% load i18n %}
 
{% block title %}{{ title }}  {% trans 'Some Organisation' %}{% endblock %}
 
{% block branding %}
<style type="text/css">
  #header
  {
    /* your style here */
  }
</style>
<h1 id="site-name">{% trans 'Organisation Website' %}</h1>
{% endblock %}
 
{% block nav-global %}{% endblock %}

This is common practice. But I noticed after this that I was still left with an annoying “Site Administration” on the main admin index page. And this string was not inside any of the template, but rather set inside the admin view. Luckily it’s quite easy to change. Assuming your language is set to English, run the following commands from your project directory:

$ mkdir locale
$ ./manage.py makemessages -l en

Now open up the file locale/en/LC_MESSAGES/django.po and add two lines after the header information (the last two lines of this example)

"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2010-04-03 03:25+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
 
msgid "Site administration"
msgstr "Main administration index"

After this, remember to run this and reload your project’s server:

$ ./manage.py compilemessages

Django tip: Automatic logins

Friday, February 12th, 2010

In the Django documentation we see the following:

When you’re manually logging a user in, you must call authenticate() before you call login().

That’s all really nice, because it makes sure that all your authentication backends are tried out; but if you want a really quick remedy for getting the job done, then you’ll need to set the user.backend property to the specific backend that authenticated the user. Beware that the Django developers can change these requirements. I wanted this to avoid writing my own backend, so I did this to log users in via a special view accepting a hash from the URL (from an e-mail that had a link that’d automatically log a user in). This could also become useful if you want to become a different user.

def get_hash(s):
    import hashlib
    m = hashlib.md5()
    m.update(str(s) + settings.LOGIN_SECRET)
    return str(m.hexdigest())
 
def auto_login(request, user_id, secret):
 
    user = get_object_or_404(User, id=user_id)
 
    if not secret == get_hash(str(user_id)):
        raise Http404()
 
    user.backend = "django.contrib.auth.backends.ModelBackend"
    login(request, user)
 
    return HttpResponseRedirect(reverse('frontpage'))

BEWARE!
I strongly suggest that you don’t log any superusers in this way. You could add a conditional statement not user.is_superuser or similar.

Django localized date template filter

Friday, July 10th, 2009

UPDATE! This is going to be redundant in Django 1.2, in which you can add DATE_FORMAT to your django.po files.

I’ve often been frustrated that using settings.DATE_FORMAT does not give a localized date. Granted that the name of a month may be localized, but the format string does not change. So let’s start out by modifying settings.py. We wrap our default date format in a ugettext so the makemessages command will detect it, and we need to make it a dummy function, because the i18n library cannot be imported in settings.py due to circularity (it depends on settings.py).

ugettext = lambda s: s
DATE_FORMAT = ugettext('N j, Y')

Run compilemessages and type in your localized date formats. Now we need a template filter that uses a localized format for calling the Django date format function. This is really simple:

from django.template.defaultfilters import stringfilter
from django.utils import dateformat
from django.utils.translation import ugettext
from django.conf import settings
 
@register.filter()
def localdate(value):
    """Format date with localized date format"""
    format = ugettext(settings.DATE_FORMAT)
    return dateformat.format(value, format)

And done. Using the filter is straight forward:


Date: {{ my_date|localdate }}

Presenting: django-simple-wiki

Monday, April 27th, 2009

It was bothering me that all the wikis I tried, all had either errors, feature lacks, too many dependencies or were simply unmaintained. So I decided to create yet another one. Curiously, the third hit when googling ‘django wiki’ is Create a wiki in 20 minutes. Luckily that’s not really true, so all the PHP guys and MediaWiki can continue breathing. This took me several days.

Google Code project page

Demo website

Hierarchy and relations
First of all, as in the Trac wiki system, I chose to create a system for hierarchy, meaning that it’s possible to create an article and then create sub-articles. The hierarchy does not support multiple inheritance, because it needs to be basis for the permission system. That’s where the relation system comes in place: All articles can contain symmetrical relations to any other articles in the hierarchy.

Parsing
Python and Django supports Markdown pretty much out of the box, so it’s an obvious choice to use this for parsing. The HTML features of normal Markdown have been removed, so all HTML is escaped in django-simple-wiki. And parsing is static, so every time a revision is created, the contents are passed and stored. This means that the contents of the article itself are not supposed to be dynamic. On the other hand, it is desirable to avoid parsing contents for every page hit. The parsing area of the application is only a few lines of code, and can be expanded if further parsing needs to be done, or someone wants to replace Markdown completely. For instance, if no parsing is done and HTML escaping is disabled, the wiki becomes a very simple CMS.

Curious issues
There are a few out standing problems:

  • Permission system is related to User entries in the Django auth system. But maybe this is too much of an annoyance, if the project already has groups setup in the existing auth system. On the other hand, other users would be bothered to setup both wiki groups and user groups, if the permission system was linked to user groups. And directly linking articles to user groups would require wiki-related groups to be created directly in the auth system.
  • Since relations are symmetrical, what should happen if one article is locked, but a user modifies it’s relations by deleting them from related articles?
  • Title editing: The title can only be created once, since it is coupled to the ’slug’ of the article. A user can deliberately create a completely different title, which is fine, but should subsequent editing be allowed, which would add complexity to the revision system?
  • Article deletion: When an article is deleted from the backend it shouldn’t worry anyone. But if the feature is added to the frontend, we would want to handle maliciousness etc. But should we really store all these files and revisions? Should we alert admins, so they can do the final cleanup?

Django tip: Translating your application names (app_label)

Sunday, July 20th, 2008

This MUST be a common issue for international developers: We use some geeky English name for our application and afterwards find that the translated admin index looks a little silly in the eyes of our native speaking users. Apparently a patch has been accepted in the Django dev version, but it’s not yet in the trunk. Here’s what to do: In your applications’ __init__.py files put:

1
2
from django.utils.translation import gettext_noop
gettext_noop("AppName")

When your run manage.py makemessages -a there will be entries for these. Make sure to remove lines saying #, fuzzy. Now all you have to do is to customize the default admin template called index.html so it will actually do the translation of the application names.

18
        <caption>{% trans app.name %}</caption>