Ole Morten Halvorsen

March 9, 2008
Simplify Django’s Free Comments Redirection

Django, with its battery included philosophy has several very nice features included. One of these cool features is the comments contrib application. In a few minutes, I was able to add commenting with Markdown highlighting to my blog. Not bad for a Django beginner.

I opted to remove the annoying “Thanks for commenting” page and redirect directly back to the blog post. The Free Comments Wiki page explained how to do just that. However, it felt like way too much hassle, too much tinkering for a simple redirect.

I live, uhm…, code by the motto: Less code is better code. Here’s my simplified approach. Add a line to your urls.py file overriding the default /comments/posted/ view.

1
2
3
4
[...]
( r'^comments/posted/$', 'blog.views.comment_posted' ),
( r'^comments/', include( 'django.contrib.comments.urls.comments' ) ),
[...]

Make sure to add the urls.py line before the inclusion of comments. Now, create the
comment_posted() method in your views.py file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from django.http import HttpResponseRedirect

from mysite.blog.models import Post

def comment_posted( request ):
    if request.GET['c']:
        comment_id, post_id  = request.GET['c'].split( ':' )
        post = Post.objects.get( pk=post_id )

        if post:
            return HttpResponseRedirect( post.get_absolute_url() )

    return HttpResponseRedirect( "/" )

That’s it. 10 lines of code and only 2 files to modify instead of 5 files and 15 lines of code. Nothing like the smell of freshly deleted code.

Comments

#1 Ole Henry Halvorsen

Posted: March 10, 2008

Nice :)

#2 Michael

Posted: March 30, 2008

Very nice… thanks!

To get this to work I did have to add the get_absolute_url method to my class but otherwise it’s a very easy way to avoid the “Thanks for commenting page”.

The docs for adding the get_absolute_url method are at:

http://www.djangoproject.com/documentation/model-api/

Leave a comment

Commenting has been disabled. This entry was posted more than 2 weeks ago.

Created by Ole Morten Halvorsen.   Powered by Django.