[Answer]-How to create a dynamic HttpResponseRedirect using Django?


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 %}


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.

Leave a comment