An ultra simple blog made with Django

Getting comments working

— Monday, December 5th 2011

I was thinking of writing my own comments app, but I thought I might as well make use of Django's native comment support. However customising the templates was pretty involved so that really helped me get to know Django's templating system.

There are 2 tweaks I've made to the way the comments work. Firstly, I've come up with a pretty good solution to the comment redirect templates (the pages displayed when you preview, post and make an error), they were just crude stand-alone pages that didn't take the site design into consideration. There are a few solutions I read about, most suggest creating your own view to intercept the comment post redirect. My approach comes from copying the comment form template preview.html in Django's core, altering it slightly and including it as a snippet in my own templates. So my view_post.html template had; {% include 'comments/blog_comment_form.html' %} Then my comments/blog_comment_form.html has; {% load comments %} {% if post %} {% get_comment_form for post as form %} {% endif %} because it can be called from either the view_post.html or the preview.html (which is used for error messages as well as previewing) template; preview.html doesn't need the {{ post }} variable to generate the form whereas blog_comment_form.html does. And of course both of those templates extend base.html so they retain the site's styling. I also wanted to change the success redirect to return to the same page from where the comment was posted from, so I added this hidden input to the form; {% if post %}
<input type="hidden" name="next" value="{{ request.get_full_path }}" />
{% else %}
<input type="hidden" name="next" value="{{ request.META.HTTP_REFERER }}" />
{% endif %}

Oh yes, I forgot there were a couple of other things I needed to do to get comments working. Comments can't be used with the vanilla Django-nonrel setup because of Django's core comments model using Textfields (which can't be indexed on GAE). Fortunately Django-nonrel has a way to individually tell certain fields to be indexed.

And lastly, yet another stumbling block was setting CSRF protection, there's good tutorials on the web on how to do this, but one thing I liked to offer is the way I chose to use RequestContext as opposed to the default Context. Most tutorials suggest passing the RequestContext as an extra argument to render_to_response(), however I think it makes more sense for a view to return direct_to_template() which uses RequestContext by default.

Comments ""


Login to post a comment