开发者

How to redirect back to same page when errors in Django comments

How do you get Django comments to redirect back to the same page where you're filling out a comment if there are errors in the comment submission form?

So basically I have a template like this:

{% 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 %}

I created my own list.html and form.html and everything looks fine. In the form.html template there is some code like this:

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

So obviously, if there is an error in开发者_如何学运维 the comment submission form, I would like the user to see the same page as before only with some errors displayed in the comments form. Or alternatively if this is not possible, just ignore the error and instead of transitioning to the preview.html template, it would just not save the comment and again go back to the page.

Any help? Note ideally I dont want to have to create a custom comments app. This functionality should be there already. I know there's a next variable you can pass (and I am doing this), but it only works if the comment form is successful.


you have to use 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')

And in template you can do this:

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

Hope this will help you :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜