python - How to create a dynamic HttpResponseRedirect using Django? -
i have 2 urls share 1 inclusion_tag, inside of inclusion tag have url displays form , form redirects 1 of 2 urls. how can make redirection dynamic? e.g. if form in url_1 redirect url_1 , if it's in url_2 redirect url_2?
here code better explanation (hopefully):
form.html
# form lives inside of inclusion tag, many urls display <form method="post" action={% url cv_toggle %}> <input type="hidden" name="c_id" value={{ c.id }}> ... {% csrf_token %} </form>
views.py
# corresponds name="cv_toggle" url def toggle_vote(request): ... next = reverse("frontpage") # url should redirect current # url requested, , not "frontpage" return httpresponseredirect(next)
you can use request object determine current url this:
<form method="post" action="..."> <input type="hidden" name="next" value="{{ request.get_full_path }}"> ... {% csrf_token %} </form>
view:
from django.utils.http import is_safe_url def toggle_vote(request): ... next_url = request.post.get('next') if not next_url or not is_safe_url(url=next_url, host=request.get_host()): next_url = reverse('frontpage') return httpresponseredirect(next_url)
django login form uses such next
field determine redirect user after logging in. can store url parameter instead of post or can use both better flexibility , easier testing.
Comments
Post a Comment