Django tip: Automatic logins

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.

Uservoice feedback widget: Changing its style

September 30th, 2009

I have a feedback tab that’s blocking vital content on a website. Here’s how to alter the style of the Uservoice Feedback Tab — for instance the vertical offset: You have to insert this AFTER your widget js code, so that it will effectively overwrite the CSS declarations generated by Uservoice. Also it’s pretty annoying that it shows up on printed media, so the last style block is to remove it from print.

<style type="text/css">
  body a#uservoice-feedback-tab,
  body a#uservoice-feedback-tab:link
  {
    margin-top: 10px !important;
  }
</style>
<style rel="stylesheet" type="text/css" media="print">
  body a#uservoice-feedback-tab,
  body a#uservoice-feedback-tab:link
  {
    display: none !important;
  }
</style>

MarkItUp Markdown footnote button

September 9th, 2009

Here’s a simple addition to markItUp, that will prompt the user for a footnote number, a footnote text and then insert the number after the selection and the footnote text at the end of the full text. As handy extra feature, the plugin will save the previous entered footnote and not ask for further numbers during the session, but instead increment the number each time the button is pressed.

Add this to your code to set.js inside your settings object:

{name:'Insert footnote',
	beforeInsert: function(h) {
		instructions = "Type in the number of the footnote:)";
		if (!h.last_footnote) {
			h.last_footnote = prompt(instructions);
		} else {
			if (!isNaN(h.last_footnote))
				h.last_footnote = parseInt(h.last_footnote) +1;
			else
				h.last_footnote = prompt(instructions);
		}
		h.footnote_content = prompt("Type in the text of the footnote:");
	},
	closeWith: function(h) {
		return '[^' + h.last_footnote + ']';
	},
	afterInsert: function(h) {
		h.textarea.value += '[^' + h.last_footnote + ']: ' +
			h.footnote_content;
	}},

And put this icon in the set’s images folder: footnote

After that be sure to modify style.css so it says something like (if 14 was the placement of the footnote button):

.markItUp .markItUpButton14 a	{
	background-image:url(images/footnote.png);
}

Django localized date template filter

July 10th, 2009

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

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?