| | 255 | Providing a comment form for authenticated users |
| | 256 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| | 257 | |
| | 258 | If a user is already authenticated, it makes little sense to display name, |
| | 259 | email, and URL fields, since these can already be retrieved from their login |
| | 260 | data and profile. In addition, some sites will only accept comments from |
| | 261 | authenticated users. |
| | 262 | |
| | 263 | To provide a comment form for authenticated users, you can manually provide the |
| | 264 | additional fields expected by the Django comments framework. For example, |
| | 265 | assuming comments are attached to the model "item":: |
| | 266 | |
| | 267 | {% if user.is_authenticated %} |
| | 268 | {% get_comment_form for item as form %} |
| | 269 | <form action="{% comment_form_target %}" method="POST"> |
| | 270 | {% csrf_token %} |
| | 271 | {{ form.comment }} |
| | 272 | {{ form.honeypot }} |
| | 273 | {{ form.content_type }} |
| | 274 | {{ form.object_pk }} |
| | 275 | {{ form.timestamp }} |
| | 276 | {{ form.security_hash }} |
| | 277 | <input type="hidden" name="next" value="{% url item_view item.id %}" /> |
| | 278 | <input type="submit" value="Add comment" id="id_submit" /> |
| | 279 | </form> |
| | 280 | {% else %} |
| | 281 | <p>Please <a href="{% url auth_login %}">log in</a> to leave a comment.</p> |
| | 282 | {% endif %} |
| | 283 | |
| | 284 | The honeypot, content_type, object_pk, timestamp, and security_hash fields are |
| | 285 | fields that would have been created automatically if you had simply used |
| | 286 | ``{{ form }}`` in your template, and are referred to in `Notes on the comment |
| | 287 | form`_ below. |
| | 288 | |
| | 289 | Note that we do not need to specify the user to be associated with comments |
| | 290 | submitted by authenticated users. This is possible because the :doc:`Built-in |
| | 291 | Comment Models</ref/contrib/comments/models>` that come with Django associate |
| | 292 | comments with authenticated users by default. |
| | 293 | |
| | 294 | In this example, the honeypot field will still be visible to the user; you'll |
| | 295 | need to hide that field in your CSS:: |
| | 296 | |
| | 297 | #id_honeypot { |
| | 298 | visibility: hidden; |
| | 299 | } |
| | 300 | |
| | 301 | If you want to accept either anonymous or authenticated comments, replace the |
| | 302 | contents of the "else" clause above with a standard comment form and the right |
| | 303 | thing will happen whether a user is logged in or not. |
| | 304 | |