1

我正在尝试使用内置的评论框架,但我无法让它工作。这是代码:

#view.py
from django.contrib.comments.forms import *
from forms import *
from models import *

def view_item_detail(request, item_id):
    item = Item.manager.get(item_id)
    form = CommentForm(item)

    if request.POST:
        form = CommentForm(request.POST)
        if form.is_valid():
            new_comment = form.save(commit=False)
            # do stuff here
            new_comment.save()
            messages.success(request, "Your comment was successfully posted!")
            return HttpResponseRedirect("")

    return render_to_response('item_detail.html', 
                          RequestContext(request, {'item': item, 
                                    'authentication': request.user.is_authenticated(), 
                                    'user': request.user, 'form': form}))

#item_detail.html
{% if authentication %}
    {% if form %}
        <form action="" method="post">{% csrf_token %}
            {{ form }}
            <p><input type="submit" name="submit" value="Submit comment" /></p>
        </form>
    {% endif %}
{% else %}
    <p>You must be logged-in to post a comment</p>
{% endif %}

我得到的错误是“'QueryDict'对象没有属性'_meta'”来自该行

form = CommentForm(request.POST)

任何帮助将不胜感激,干杯。

4

1 回答 1

1

抱歉,在阅读您对我上一个答案的评论后,如果您使用的是内置评论框架,则无需在视图中包含评论表单:

from forms import *
from models import *

def view_item_detail(request, item_id):
    item = get_object_or_404(Item, pk=item_id)

    return render_to_response('item_detail.html', 
                          RequestContext(request, {'item': item, 
                                    'authentication': request.user.is_authenticated(), 
                                    'user': request.user,}))

现在确保你的 urls.py 中有这个:

urlpatterns = patterns('',
    ...
    (r'^comments/', include('django.contrib.comments.urls')),
    ...
)

'django.contrib.comments'添加到您的 INSTALLED_APPS 和 syncdb'd

现在在你的item_detail.html文件中你应该添加:

{% load comments %}

您希望显示评论的位置:

{% render_comment_list for item %}

您希望显示添加评论表单的位置:

{% if authentication %}
    {% get_comment_form for item as form %}
    <form action="{% comment_form_target %}" method="post">
        {{ form }}
        <tr>
            <td></td>
            <td><input type="submit" name="preview" class="submit-post" value="Preview"></td>
        </tr>
    </form>
{% endif %}

阅读文档here和自定义阅读this页面。

作为文档的一部分:

要在评论发布后指定要重定向到的 URL,您可以在评论表单中包含一个名为 next 的隐藏表单输入。例如:

<input type="hidden" name="next" value="{% url my_comment_was_posted %}" />

(为您的示例编辑):

{% if authentication %}
    {% get_comment_form for item as form %}
    <form action="{% comment_form_target %}" method="post">
        {{ form }}
        <tr>
            <td></td>
            <input type="hidden" name="next" value="{{ item.get_absolute_url }}" />
            <td><input type="submit" name="preview" class="submit-post" value="Preview"></td>
        </tr>
    </form>
{% else %}
    <p>You must be logged-in to post a comment</p>
{% endif %}
于 2011-04-14T02:18:24.290 回答