2011-07-23 45 views
2

如果評論提交表單中存在錯誤,如何將Django評論重定向回填寫評論的相同頁面?如何在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模板,它將不會保存評論,並再次返回到頁面。

任何幫助?注意理想情況下,我不想創建自定義評論應用程序。這個功能應該已經存在了。我知道你可以傳遞下一個變量(而且我正在這樣做),但它只有在評論表單成功時纔有效。

回答

2

,你必須使用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%} 

希望這將幫助你:)

相關問題