我正在尝试将用户重定向回发布评论的页面。我找到了post on Django's site,但我做错了,因为它不会重定向回来。
应该在哪里放置输入才能正确重定向?
{% 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>
答案 0 :(得分:1)
也许您不需要在模板中检查 next 变量。您可以尝试更改:
{% if next %}<input type="hidden" name="next" value="{{ next }}" />{% endif %}
只是:
<input type="hidden" name="next" value="/added/comment/page/" />
如果您使用views.py,从那里重定向似乎更明显,至少对我而言,因为它有助于将关注点远离模板:
from django.http import HttpResponseRedirect
HttpResponseRedirect("/path/to/redirect")
答案 1 :(得分:1)
axel22's answer的问题在于它需要更改每个需要注释表单的模板 - 如果您有多个可以注释的对象类型,那么这不是DRY。
不幸的是,我还在寻找一个有效的答案。
答案 2 :(得分:0)
如果您在模板中使用{% render_comment_form for object %}
标记,只需添加{% url object's_named_view object.id as next %}
之类的内容,或将其与{% with object.get_absolute_url as next %}
... {% endwith %}
结构一起打包。
答案 3 :(得分:0)
请在此处查看我的解决方案:Django: Redirect to current article after comment post
它基本上使用由评论发布网址触发的视图,该视图会重定向回原始引荐网页。