Search code examples
djangodjango-urlsdjango-url-reverse

How to add a URL fragment to HttpResponseRedirect (reverse ('name_view'))' in Django?


Can I add an id to my method 'HttpResponseRedirect (reverse ('name_view'))'?

I have a simple form, the user can see the message ('!All is good! :).') after sending it. But it is at the bottom of the page and the user is redirected to the top of the page. Can I do a redirection to the bottom of the page (after saving the form)? If so, how to achieve it?

views.py

if request.method == 'POST':
    contact_form = ContactForm(request.POST)
    if contact_form.is_valid():
        contact_form.save()
        messages.success(request, '!All is good! :).')
        return HttpResponseRedirect(reverse('app:home'))

else:
    contact_form = ContactForm()

In my case, I am looking for something like:

return HttpResponseRedirect(reverse('app:home#message_sending_section'))

home.html

<section class="module divider-top" id="message_sending_section">
[...]
                        {% if messages %}
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            {% for message in messages %}
                            {% if message.tags %}
                            <span class="alert-inner--icon"><i class="fas fa-check"></i></span>
                            <span class="alert-inner--text"></strong>{{ message.tags }}</strong></span>
                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                            {% endif %}
                                {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %}
                                {{ message }}
                            {% endfor %}
                        </div>
                        {% endif %}
[...]
</section>

Solution

  • The anchor is not part of the URL pattern that is the argument to reverse, but is appended to the generated URL that is the result of that call. So:

    return HttpResponseRedirect("{}#message_sending_section".format(reverse('app:home')))