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