简体   繁体   中英

Django user authentication does not work, how can I fix my login?

I am using the django-email-verification app and I had to change how a User is signed up but I left the login authentication part the same. Every time I try to login it does not allow me to sign in and says that the credentials are wrong. Also I used emails as usernames. I'm thinking its the:
user = auth.authenticate(username=request.POST['username'], password=request.POST['password'])
that needs to be changed. Please how do I fix the login?

from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib import auth
from django.contrib.auth import get_user_model
from django_email_verification import sendConfirm


def signup(request):
    if request.method == 'POST':
        if request.POST['pass1'] == request.POST['pass2']:
            try:
                user = User.objects.get(username=request.POST['username'])
                return render(request, 'accounts/signup.html', {'error': 'Email is already registered'})
            except User.DoesNotExist:
                '''user = User.objects.create_user(request.POST['username'], password=request.POST['pass1'])
                auth.login(request, user)'''
                user = get_user_model().objects.create(username=request.POST['username'], password=request.POST['pass1'], email=request.POST['username'])
                sendConfirm(user)
                return redirect('home')
        else:
            return render(request, 'accounts/signup.html', {'error': 'Passwords must match'})
    else:
        return render(request, 'accounts/signup.html')

def login(request):
    if request.method == 'POST':
        user = auth.authenticate(username=request.POST['username'], password=request.POST['password'])
        if user is not None:
            auth.login(request, user)
            return redirect('home')
        else:
            return render(request, 'accounts/login.html',{'error':'username or password is incorrect.'})
    else:
        return render(request, 'accounts/login.html')

def logout(request):
    if request.method == 'POST':
        auth.logout(request)
        return redirect('home')

The problem is not with authenticating, but with creating the user. Passwords are normally hashed . The .create(…) function [Django-doc] will not hash these, you can make use of .create_user(…) [Django-doc] instead:

user = get_user_model().objects.
    username=request.POST['username'],
    password=request.POST['pass1'],
    email=request.POST['username']

The .create_user(…) function is a function the manager of the user model normally should provide. This will for (most) user models store the hash of the password in the database.

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