简体   繁体   中英

Django doesn't authenticate user

I'm trying to build a login page on django. First i tried using:


from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.models import User, auth

# Create your views here.

def login(request):
    if request.method== 'POST':
        username = request.POST['username']
        password = request.POST['password']

        User = auth.authenticate(username=username,password=password)

        if User is not None:
            auth.login(request, User)
            return redirect("/")
        else:
            messages.info(request,'invalid credentials')
            return redirect('login')

    else:
        return render(request,'login.html') 

but i received an error saying: MultiValueDictKeyError at /accounts/login. Then i changed it to:

def login(request):
    if request.method== 'POST':
        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 redirect("/")
        else:
            messages.info(request,'invalid credentials')
            return redirect('login')

    else:
        return render(request,'login.html') 

then only problem now is that it always shows invalid credentials even when i created new user. Help please.

There was a mistake in defining the name on the html file. The correct way is as follows:

<input type="text" name="username" placeholder="Enter username"><br>
<input type="password" name="password" placeholder="Enter Password"><br>

first of all you need to import these function in django.contrib.auth

from django.contrib.auth import authenticate, login
""" 
     from django.contrib.auth.models import User
     don't need this import since authencate will directly
     check if the user you trying to authencate exist in the User model
"""

def login(request):
if request.method== 'POST':
    username = request.POST.get('username')
    password = request.POST.get('password')

    user = authenticate(username=username,password=password)

    if user is not None:
        login(request, user)
        return redirect("/")
    else:
        messages.info(request,'invalid credentials')
        return redirect('login')

else:
    return render(request,'login.html') 

try these and let me know if that help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM