Search code examples
djangodjango-authentication

When ever I log in and I am redirect to the 'next' parameter, a trailing slash is automatically added to the url, making it double slashes


I have created views in Django that use LoginRequiredMixin. However, whenever I log in and am to be redirected to another url, the url I am redirected to ends with multiple slashes instead of the usual 1 slash at the end of a django url. One of my views:

class BookListView(LoginRequiredMixin, ListView):

    model = Book
    # paginate enables the list view to fetch a certain number of records per page. This is
    # useful when the records are plenty and it is not possible to display all in one page.
    paginate_by = 3 

My login.html template:

{%extends 'catalog/base_generic.html'%}

{%block content%}

{%if form.errors %}
    <p>Your username and password didn't match. Please try again.</p>
{% endif %}

{%if next %}
    {% if user.is_authenticated %}
        <p>Your account doesn't have access to this page. To proceed,
            please login with an account that has access.
        </p>
    {% else %}
        <p>Please login to view this page.</p>
    {% endif %}
{% endif %}

<form method="POST", action="{% url 'login' %}">
    {% csrf_token %}
    <table>
        <tr>
            <td>{{form.username.label_tag}}</td>
            <td>{{form.username}}</td>
        </tr>
        <tr>
            <td>{{form.password.label_tag}}</td>
            <td>{{form.password}}</td>
        </tr>
    </table>
    <input type="submit" value="Login"/>
    <input type="hidden" name="next" value={{next}}/>
</form>

<P>
    <a href="{% url 'password_reset' %}">Forgot Password?</a>
</P>

{% endblock %}

When I am just logging in, all seems Okay: Login Page

However, after login, this happens: Error Message with multiple slashes at the end

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/catalog/books///
Using the URLconf defined in locallibrary.urls, Django tried these URL patterns, in this order:

admin/
catalog/ [name='index']
catalog/ books/ [name='books']
catalog/ book/<int:pk>/ [name='book-detail']
catalog/ authors/ [name='authors']
catalog/ author/<int:pk>/ [name='author-detail']
accounts/
^static/(?P<path>.*)$
The current path, catalog/books///, didn’t match any of these.

You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

I can't figure out what I am doing wrong. Please help!


Solution

  • you forgot some quotes around {{ next }}

    change it to

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