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.