user2151557 February 2016

Django login gives http 500 error

So I'm making a login system for my Django application. It works on my dev side absolutely fine, but in prod it doesn't work if I submit the correct username and password (It gives a 500 error). I'm not sure which of the two lines I've pointed out in views.py is the issue, but I figure it must be one of those two since if I do enter an incorrect user then I get redirected fine, even in prod.

The code on my dev and prod side are EXACTLY the same - the only difference is in the settings

   DEBUG = True
   ALLOWED_HOSTS = []

^ The above is my dev settings, but in prod DEBUG is False and ALLOWED_HOSTS has been filled out with the appropriate names.

In views.py:

def user_login(request):
if request.method == "POST":
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None and user.is_active:
        login(request=request, user=user) <- This line
        return render(request, 'site/homepage.html') <- Or this line
    else:
        return render(request, 'site/login.html', {'incorrect': True})
else:
    return render(request, 'site/login.html', {})

In login.html:

{% block content %}
{% if user.is_authenticated %}
<div class="title">
    <h2>Error</h2>
</div>
<p>You have already logged in, {{ user.firstname }}. Please logout to login as another user!</p>
{% else %}
<div class="title">
    <h2>Login</h2>
</div>
{% if incorrect %}
<p>You have entered the wrong username and/or password.<br />
Please try again</p>
{% elif unauthorised %}
<p>You must login before trying to access that page!<br /></p>
{% endif %}
<form id="login_form" method="post" action="#">
{% csrf_token %}
<label>Username: <input type="text" name="username" value="" size="50" /></        

Answers


doru February 2016

In the form, the action attribute doesn't have any value so you don't send anything to the view. It should be "."

<form id="login_form" method="post" action=".">

or

<form id="login_form" action="{% url 'login' %}" method="post">

if your login url name is login.


Limbail February 2016

Tested in my server this work, if not, tell us the new error.

view.py:

def login_user(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None and user.is_active:
            login(request, user)
            return HttpResponseRedirect('/')
        else:
            return render(request, 'login/auth.html', {'incorrect': True})
    else:
        return render(request, 'login/auth.html', {})

Post Status

Asked in February 2016
Viewed 2,675 times
Voted 5
Answered 2 times

Search




Leave an answer