Reusable App: Authenticated Comments

Tue 04 August 2009 by Thejaswi Puthraya

This app had been on my todo list for a long time. Today, no matter how much I tried to procrastinate, I could not ignore it and hence decided to scratch my itch and get it done. I swore I wouldn't even get up for a glass of water until it was done. Luckily, this took lesser time than I anticipated and I was spared of breaking my resolve!

There are certain sites that require only authenticated users to post comments, this app specifically targets such cases.

It builds on my previous posts sans the javascript hack. To make the code very condense and easy to use, it uses "Two-phased template rendering" that I saw in Ella via Adrian Holovaty's post. From a security point, it auto-escapes django template code injected in through the comments in the middleware.

How to use it

  • Fetch the source from here and copy the auth_comments app over to your project and reference it under the INSTALLED_APPS in settings.py
  • Add the COMMENTS_APP attribute in settings.py and set the value to auth_comments
  • Make sure that you have the following TEMPLATE_CONTEXT_PROCESSORS activated in your settings.py.
TEMPLATE_CONTEXT_PROCESSORS=(
  "django.core.context_processors.auth",
  "django.core.context_processors.request",
  "django.core.context_processors.media"
 )
  • Append the auth_comments/templates directory in the TEMPLATE_DIRS attribute of settings.py
  • Activate the comment urls in your project's urls.py
(r'^comment/', include('django.contrib.comments.urls')),
  • In your templates, when you want to render the authenticated comment form, just use the following code.
{% load auth_comments %}
...
{% render_auth_comment_form for app.model object_pk %}

This code is equivalent to

{% if request.user.is_authenticated %}
  {% render_comment_form for app.model object_pk %}
{% else %}
  Some standard message to be shown if user not logged in.
{% endif %}

The standard message is picked up from the DEFAULT_UNAUTH_COMMENT_MESSAGE attribute of settings.py which you can set to override the default message.

If you liked the app, do let me know. Also please fork and improve the code if you wish to improve it.