문제

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 :)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top