我完全理解有关在 Django 中扩展评论应用程序的文档,并且真的想坚持使用自动功能 ...

在当前的应用程序中,我完全没有必要将“URL”与评论一起提交。

存在 微创 默认设置, 我怎样才能防止这个字段出现在评论表单中?

使用 Django 1 或 Trunk,以及尽可能多的通用/内置插件(通用视图、默认注释设置等)到目前为止我只有一个通用视图包装器)。

有帮助吗?

解决方案

这在下面有详细记录 自定义评论框架.

您的应用程序将使用的所有内容是 get_form, ,返回的子类 CommentForm 弹出 url 字段。就像是:

class NoURLCommentForm(CommentForm):
    """
    A comment form which matches the default djanago.contrib.comments one, but
    doesn't have a URL field.

    """
NoURLCommentForm.base_fields.pop('url')

其他提示

由于某种原因我无法评论 SmileyChris 的帖子,所以我将其发布在这里。但是,我仅使用 SmileyChris 的回复就遇到了错误。您还必须覆盖 get_comment_create_data 函数,因为 CommentForm 将查找您删除的那些 Post 键。这是我删除三个字段后的代码。

class SlimCommentForm(CommentForm):
"""
A comment form which matches the default djanago.contrib.comments one, but with 3 removed fields
"""
def get_comment_create_data(self):
    # Use the data of the superclass, and remove extra fields
    return dict(
        content_type = ContentType.objects.get_for_model(self.target_object),
        object_pk    = force_unicode(self.target_object._get_pk_val()),
        comment      = self.cleaned_data["comment"],
        submit_date  = datetime.datetime.now(),
        site_id      = settings.SITE_ID,
        is_public    = True,
        is_removed   = False,
    )


SlimCommentForm.base_fields.pop('url')
SlimCommentForm.base_fields.pop('email')
SlimCommentForm.base_fields.pop('name')

这是您要覆盖的函数

def get_comment_create_data(self):
    """
    Returns the dict of data to be used to create a comment. Subclasses in
    custom comment apps that override get_comment_model can override this
    method to add extra fields onto a custom comment model.
    """
    return dict(
        content_type = ContentType.objects.get_for_model(self.target_object),
        object_pk    = force_unicode(self.target_object._get_pk_val()),
        user_name    = self.cleaned_data["name"],
        user_email   = self.cleaned_data["email"],
        user_url     = self.cleaned_data["url"],
        comment      = self.cleaned_data["comment"],
        submit_date  = datetime.datetime.now(),
        site_id      = settings.SITE_ID,
        is_public    = True,
        is_removed   = False,
    )

我的快速而肮脏的解决方案:我将“电子邮件”和“网址”字段设置为隐藏字段,并使用任意值来消除“此字段为必填”错误。

它并不优雅,但速度很快,而且我不必子类化 CommentForm。所有添加评论的工作都在模板中完成,这很好。它看起来像这样(警告:未经测试,因为它是我实际代码的简化版本):

{% get_comment_form for entry as form %}

<form action="{% comment_form_target %}" method="post"> {% csrf_token %}

{% for field in form %}

    {% if field.name != 'email' and field.name != 'url' %}
        <p> {{field.label}} {{field}} </p>
    {% endif %}

{% endfor %}

    <input type="hidden" name="email" value="foo@foo.foo" />
    <input type="hidden" name="url" value="http://www.foofoo.com" />

    <input type="hidden" name="next" value='{{BASE_URL}}thanks_for_your_comment/' />
    <input type="submit" name="post" class="submit-post" value="Post">
</form>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top