2

如果评论提交表单中有错误,如何让 Django 评论重定向回您填写评论的同一页面?

所以基本上我有一个这样的模板:

{% block content %}
{% render_comment_form for show %}
{% get_comment_count for show as comment_count %}
<div id="comments-count">
{% if comment_count == 0 %}
    No comments yet. Be the first!
{% else %}
    Number Of Comments: {{ comment_count }}
{% endif %}
</div>
{% if comment_count > 0 %}
{% render_comment_list for show %}
{% endif %}
{% endblock %}

我创建了自己的 list.html 和 form.html,一切看起来都很好。在 form.html 模板中有一些这样的代码:

<ul class="form-errors">
{% for field in form %}
    {% for error in field.errors %}
    <li>{{ field.label }}: {{ error|escape }}</li>
    {% endfor %}
{% endfor %}
</ul>

所以很明显,如果评论提交表单中有错误,我希望用户看到与以前相同的页面,只是评论表单中显示了一些错误。或者,如果这是不可能的,只需忽略错误,而不是转换到 preview.html 模板,它不会保存评论并再次返回页面。

有什么帮助吗?请注意,理想情况下,我不想创建自定义评论应用程序。这个功能应该已经存在了。我知道你可以传递下一个变量(我正在这样做),但它只有在评论表单成功时才有效。

4

1 回答 1

1

你必须使用 HttpResponseRedirect

from django.http import HttpResponseRedirect

def comment_form(request):
    error = request.GET.get('error', None)
    requestDict = {'error': error}
    return render_to_response('comments.html', requestDict, context_instance=RequestContext(request))

def post_comment(request):
    ....
    your code
    ....
    if something_goes_wrong:
        HttpResponseRedirect('project/comment_form/?error=ThereisProblem')

在模板中你可以这样做:

{If error %}
   <h1>{{error}}<h1>
{%else%}
    render comments...
{%endif%}

希望对你有帮助 :)

于 2011-07-24T10:07:05.637 回答