开发者

Django: Redirect after posting a comment

I am trying to redirect the user back to the page where the comment was posted. I found this post on Django's site but I am doing something wrong because it won't redirect back.

Where should the input be placed to have it properly redirected?

{% load comments i18n %}
<form action="{% comment_form_target %}" method="post">{% csrf_token %}
  {% if next %}<input type="hidden" name="next" value="{{ next }}" />{% endif %}
  {% for field in form %}
    {% if field.is_hidden %}
      {{ field }}
    {% else %}
      {% if field.errors %}{{ field.errors }}{% endif %}
            <input type="hidden" name="next" value="{% url proposal proposal.id %}" />
      <p
        {% if field.errors %} class="error"{% endif %}
        {% ifequal field.name "honeypot" %} style="display:none;"{% endifequal %}
         {% ifequal field.name "name" %} style="display:none;"{% endifequal %}
         {% ifequal field.name "email" %} style="display:none;"{% endifequal %}
         {% ifequal field.name "url" %} style="display:none;"{% endifequal %}
         {% ifequal field.name "title" %} style="display:none;"{% endifequal %}>
        <!-- {{ field.label_tag }}  -->{{ field }}
      </p>
    {% endif %}
  {% endfor %}
  <p class="submit">
    <!-- <button><input type="submit" name="post" value="{% trans "Send" %}" /></button> -->
        <button type="submit">Send</button>
    <开发者_如何学运维!-- <input type="submit" name="preview" class="submit-preview" value="{% trans "Preview" %}" /> -->
  </p>
</form>


Maybe you don't need to check for next variable in your template. You could try changing:

{% if next %}<input type="hidden" name="next" value="{{ next }}" />{% endif %}

to just:

<input type="hidden" name="next" value="/added/comment/page/" />

In case you use views.py, redirecting from there seems more obvious, at least for me, as it helps keep the concern away from the template:

from django.http import HttpResponseRedirect
HttpResponseRedirect("/path/to/redirect")


The problem with axel22's answer is that it requires a change to each template that requires the comment form - if you have multiple object types that can be commented on, this is not DRY.

Unfortunately, I'm also still looking for an answer that works.


if you are using {% render_comment_form for object %} tag in your template, just add something like {% url object's_named_view object.id as next %} or wrap it with {% with object.get_absolute_url as next %} ... {% endwith %} construction.


See my solution here: Django: Redirect to current article after comment post

It basically uses a view that's triggered by the comment post url which redirects back to the original referrer page.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜