djangopython-3.xauthenticationform-authentication

"user = authenticate(request, username=username, password=password)" user is none


def login_page(request):
    form = LoginForm(request.POST or None)
    context = {
        "form": form
    }
    print("User logged in")
    #print(request.user.is_authenticated())
    if form.is_valid():
        print(form.cleaned_data)
        username  = form.cleaned_data.get("username")
        password  = form.cleaned_data.get("password")
        user = authenticate(request, username=username, password=password)
        print(user)
        print(request.user.is_authenticated())
        if user is not None:
            print(request.user.is_authenticated())
            login(request, user)
            # Redirect to a success page.
            context['form'] = LoginForm()
            return redirect("/")
        else:
            # Return an 'invalid login' error message.
            print("Error")

    return render(request, "auth/login.html", context)

Hello, I have started playing around in Django, but in a tutorial, when a tutor clicks submit, it authenticates the user ... I found almost the same problem on stack overflow already, but problem is, that a guy had a string instead of variables ( username = 'username' ) but problem is that when I click submit I get an error :

User logged in
{'username': 'test123', 'password': 'test'}
None
False
Error

User logged in is just a string in print() 
None <- print(user)
False <- print(request.user.is_authenticated())
Error <- else: print("Error")

I am struggling for an hours with this problem ( we have the same version of Django ) Django==1.11.4


Solution

  • So I am not totally sure what exactly is causing your problems here.

    I know this probably isn't what they do in the tutorial, but my suggestion to you would be to use the built in Django authentication views. That way you don't have to repeat code that is already done for you.

    The views are very simple to use. All you need to do is set the proper route in your URL and then create a template under the directory 'registration/login.html'.

    First set proper settings in your settings.py file(I'm including the login and logout steps because they go hand-in-hand):

    LOGIN_REDIRECT_URL = '/page/you/redirect/to/'
    LOGOUT_REDIRECT_URL = '/your/login/page/'
    

    Then set URLs:

    urls.py

    from django.conf.urls import url
    from django.contrib.auth import views as auth_views
    from django.conf import settings
    
    urlpatterns = [
        url(r'^login/$', auth_views.login, {'redirect_authenticated_user': True},name='login'),
        url(r'^logout/$', auth_views.logout, {'next_page': settings.LOGOUT_REDIRECT_URL}, name='logout'), 
    ]
    

    Then finally in your templates folder that is within the same app as the urls.py file where you put the login and logout routes, create a folder named "registration" and create an html file called "login.html".

    Finally, your "login.html" file can simply be this:

    {% block title %}Login{% endblock %}
    
    {% block content %}
        <body>
            <h2>Login</h2>
            <form method="post">
                {% csrf_token %}
                {{ form.as_p }}
                <button type="submit">Login</button>
            </form>
        </body>
    
    
    {% endblock %}
    

    When you want to logout, just put a button wherever you want and link it to "/logout". And after that, authentication is done!