0
votes

I'm new to the django login setup. And I've researched my way to something that seemed good and copied that.

I have discovered this decorator: @user_passes_test

That helps me make sure people with the right access to my "/dashboard" page have logged in. After getting redirected to login the url is:

placeholder.it/login/?next=/dashboard/%3Fcvr%3D24256790

BUT the user always get send to:

placeholder.it/accounts/loggedin

insted of the next url. How come??

This is some of my code: views.py

@user_passes_test(lambda u:u.is_staff, login_url='/accounts/login/')
def dashboard(request):
    cvr = request.GET.get('cvr', '')
    return render(request,'dashboard.html', { "cvr": cvr})    


def login(request):
    c = {}
    c.update(csrf(request))
    return render_to_response('login.html', c)    


def auth_view(request):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user = auth.authenticate(username=username, password=password)    

    if user is not None:
        auth.login(request, user)
        return HttpResponseRedirect('/accounts/loggedin')
    else:
        return HttpResponseRedirect('/accounts/invalid')

login.html

{% extends "base.html" %}    

{% block content %}    

  {% if form.errors %}
    <p class="error">Sorry, that's not a valid username or password</p>
  {% endif %}    

  <form action="{% url 'auth' %}" method="post">{% csrf_token %}
    <label for="username">User name:</label>
    <input type="text" name="username" value="" id="username">
    <label for="password">Password:</label>
    <input type="password" name="password" value="" id="password">    

    <input type="submit" value="login" />

  </form>    

  <br>
  Login to access all sites    

{% endblock %}

urls.py

url(r'^accounts/login/$', views.login, name='login'),
url(r'^accounts/auth/$', views.auth_view, name='auth'),
url(r'^dashboard/$', views.dashboard, name='dashboard'),

Appreciate any help <3

2

2 Answers

4
votes

Your decorator is sending the users who are not logged in to the login view. The login page has a form that posts to the auth_view view. The auth view explicitly redirects every logged in user to /accounts/loggedin.

You're redirecting users on your own, through the codes in auth_view. Your code doesn't respect the next query parameter (that the decorator is appending to the login url). Your code should read the value of the next parameter and put it in a hidden field inside the form. On the POST request to auth_view, you should read that value and redirect the user to that url.

0
votes

There is an inbuilt decorator to handle if user has logged in or not Import the following

from django.contrib.auth.decorators import login_required

And place the decorator above your function:

@login_required(redirect_field_name='next') 
def page(request):

Add this to your login template

input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}"