Pompeyo
Pompeyo

Reputation: 1469

How to create a dynamic HttpResponseRedirect using Django?

I have two urls that share one inclusion_tag, inside of the inclusion tag I have another url that displays a form and this form redirects to one of the two urls. How can I make this redirection dynamic? E.g. If the form is in the url_1 redirect to url_1 and if it's in the url_2 redirect to url_2?

Here is my code for a better explanation (hopefully):

form.html

# This form lives inside of an inclusion tag, so many urls could display it
<form method="POST" action={% url cv_toggle %}>
    <input type="hidden" name="c_id" value={{ c.id }}>
    ...
    {% csrf_token %}
</form>

views.py

# corresponds to name="cv_toggle" as a url
def toggle_vote(request):
    ...
    next = reverse("frontpage") # this url should redirect to the current
                                # url requested, and not just "frontpage"
    return HttpResponseRedirect(next)

Upvotes: 0

Views: 802

Answers (1)

HankMoody
HankMoody

Reputation: 3174

You can use the request object to determine current URL like 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 to determine where to redirect user after logging in. You can store this URL also as GET parameter instead of POST or You can use both for better flexibility and easier testing.

Upvotes: 1

Related Questions