Django: redirect after posting a comment

I am trying to redirect the user to the page on which the comment was posted. I found this post on the Django website , but I am doing something wrong because it is not being redirected back.

Where should the input be placed for proper redirection?

{% 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> 
+4
source share
4 answers

You may not need to check the next variable in the template. You can try:

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

just:

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

If you use view.py, redirecting from there seems more obvious, at least for me, as it helps to keep the attention from the template:

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

The problem with axel22 answer is that for each template a change is required for the comment form - if you have several types of objects that you can comment on, this is not DRY.

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

+1
source

if you use the {% 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 %} .

0
source

See my solution here: Django: Redirecting to the current article after posting a comment

Mostly the view is used, caused by the comment URL, which redirects back to the referrer's original page.

0
source

Source: https://habr.com/ru/post/1342009/


All Articles