3

我用我自己的覆盖了评论框架的form.html模板

{% load comments i18n %}
<form action="{% comment_form_target %}" method="post">{% csrf_token %}
    <div><input type="hidden" name="next" value="{{ request.get_full_path }}" /></div>

    {% for field in form %}
        {% if field.is_hidden %}
            <div>{{ field }}</div>
        {% else %}
            {% if field.name != "name" and field.name != "url" and field.name != "email" %}
                {% if field.errors %}{{ field.errors }}{% endif %}
                <p
                    {% if field.errors %} class="error"{% endif %}
                    {% ifequal field.name "honeypot" %} style="display:none;"{% endifequal %}
                >
                    {{ field.label_tag }}<br />
                    {{ field }}
                </p>
            {% endif %}
        {% endif %}
    {% endfor %}

    <p class="submit">
        <input type="submit" name="post" class="submit-post" value="{% trans "Post" %}" />
    </p>
</form>

它几乎只呈现所需的隐藏字段(为了安全)和评论字段。全部comment.user自动设置为当前登录用户request.user。这是呈现的 HTML:

<form action="/comments/post/" method="post"><div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='bd05094c2e3ba80e1fbec8a4237b132c' /></div>
    <div><input type="hidden" name="next" value="/doors/orders/1/" /></div>
    <div><input type="hidden" name="content_type" value="doors.order" id="id_content_type" /></div>
    <div><input type="hidden" name="object_pk" value="1" id="id_object_pk" /></div>
    <div><input type="hidden" name="timestamp" value="1333125894" id="id_timestamp" /></div>
    <div><input type="hidden" name="security_hash" value="c6791aafdd682cd8db5595681073c9a21c5fe7dd" id="id_security_hash" /></div>
    <p>
        <label for="id_comment">Comment</label><br />
        <textarea id="id_comment" rows="10" cols="40" name="comment"></textarea>
    </p>
    <p style="display:none;" >
        <label for="id_honeypot">If you enter anything in this field your comment will be treated as spam</label><br />
        <input type="text" name="honeypot" id="id_honeypot" />
    </p>
    <p class="submit">
        <input type="submit" name="post" class="submit-post" value="Post" />
    </p>
</form>

问题是我注意到如果登录的用户没有电子邮件,那么评论会转到preview.html(我没有覆盖)。这是屏幕截图:

这是一个安全问题,因为它允许某人在发布之前更改他们的姓名而不是使用登录用户的姓名(当我列出评论时,我使用comment.user.get_full_name而不是,comment.name所以这不是问题,但它仍然可能令人困惑,比如说,管理页面)。

所以我的问题是:

  1. 如何允许没有电子邮件的用户发表评论?
  2. 我怎么不允许表格去preview.html
  3. 我的代码和设计到目前为止还好吗?
4

1 回答 1

2

好吧,您可以使用自定义文档来创建一个自定义应用程序来处理来自评论框架的评论。您应该COMMENTS_APP = 'my_comment_app'在您的设置文件中设置并在您的应用程序中指定一个get_form()方法,该方法__init__.py应该返回您的自定义表单。

自定义表单应该基于contrib.comments.forms.CommentForm并且看起来应该是这样的:

class CustomForm(comment_forms.CommentForm):
    def __init__(*args, **kwargs):
        super(CustomFors, self).__init__(*args, **kwargs)
        self.fields["email"].required = False

preview.html呈现是因为表单包含错误(需要 emai,但用户没有它,因此未填充)。如果没有错误 - 将不会显示预览。

于 2012-07-20T09:07:33.257 回答