Only signed in users can comment

This page describes how to setup django-comments-xtd so that only registered users can write comments or flag them. That means mere visitors will be able to see the comments but won’t be able to send them. In order to do so a visitor must login first. The following instructions use the Django admin interface to login and logout users.

Simple example using only the backend

A simple site using django-comments-xtd can be represented by the Simple project.

Customize the simple project

The Simple project is a basic example site that allows both, visitors and registered users, post comments to articles. It has been introduced in the Demo projects page: Simple project. The example loads a couple of articles to illustrate the functionality.

If you have already setup the Simple project, and have sent a few testing comments to see that visitors and registered users can comment, add the COMMENTS_XTD_APP_MODEL_OPTIONS entry at the bottom of the module to allow only registered users to post comments:

    'default': {
        'allow_flagging': False,
        'allow_feedback': False,
        'show_feedback': False,
        'who_can_post': 'users'

Once the change is saved and Django has reloaded check that, as before, registered users can comment without issues, however visitors get the HTTP-400 page (Bad Request).

As a final step to customize the simple example site either edit templates/comments/form.html or templates/articles/article_detail.html to display a message inviting visitors to login or register instead of showing the post comment form.

As an example, here is a modified version of the article_detail.html template of the Simple project that displays a message with a link to the login page when the user is not authenticated:


  {% if object.allow_comments %}
    {% if user.is_authenticated %}
      <div class="comment">
        <h5 class="text-center">Post your comment</h5>
        <div class="well my-4">
          {% render_comment_form for object %}
    {% else %}
      <p class="text-center">
        Only registered users can post comments. Please,
        <a href="{% url 'admin:login' %}?next={{ object.get_absolute_url }}">login</a>.
    {% endif %}
  {% else %}
    <h5 class="text-center">comments are disabled for this article</h5>
  {% endif %}