Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django login/logout

Tags:

python

django

I'm trying to create a login and logout page with django. The problem I have is that when I submit the form, it doesn't go the url which I specified. When I click the login button, I want it to go to http://127.0.0.1:8000/home/ but instead, it goes to http://127.0.0.1:8000/?next=/home/.

Below is my login/logout code in my view.py:

def login(request):
    def errorHandler(error):
    return render_to_response('login.html', {'error' : error})
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username = username, password = password)
        if user is not None:
            if user.is_active:
                authLogin(request, user)
                fullName = user.get_full_name
                return render_to_response('logged_in.html', {'full_name': fullName})
            else:
                error = 'Account disabled.'
        return errorHandler(error)
        else:
            error = 'Invalid details entered.'
        return errorHandler(error)

    return render_to_response('login.html')

@login_required
def logout(request):
    authLogout(request)
    return render_to_response('logged_in.html')

my login.html:

{% extends "base.html" %}

{% block content %}

  {% if error %}
    <p><b><font color="red">Error: </font></b>{{ error }}</p>
  {% endif %}

  <form action="/home/" method="post">
    <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" />
    <input type="hidden" name="next" value="{{ next|escape }}" />
  </form>

{% endblock %}

my logged_in.html:

{% extends "base.html" %}

{% block name %}{{ full_name }} is {% endblock %}

{% block content %}
    <p><a href='/'>Logout</a></p>
{% endblock %}

url:

(r'^$', 'myapp.views.login'),
(r'^home/$', 'myapp.views.logout'), 

Please help

like image 424
makezi Avatar asked Nov 05 '22 22:11

makezi


1 Answers

The problem is that you don't actually login the user, the form sends unauthenticated user to /home/, which can't process, because it requires login. :-) So it redirects user to login view, storing the destination in next parameter.

Solution: <form action="" method="post">

like image 91
DrTyrsa Avatar answered Nov 09 '22 02:11

DrTyrsa