为什么我登录django时,会抛出用户名或密码不存在的错误

问题描述 投票:0回答:1

我在终端里有这个

'invalid_login': 'Please enter a correct %(username)s and password. Note that both fields may be case-sensitive.', 'inactive': 'This account is inactive.'}
[

但是,我已经通过浏览器保存了我的用户名和密码,设置了很常见的用户名和密码,不可能写错

可能是注册时使用的表单有问题,或者是注册表的问题,或者是模型的问题?

我的模特

from django.db import models
from django.contrib.auth.models import User


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=255, blank=True)
    last_name = models.CharField(max_length=255, blank=True)
    bio = models.CharField(max_length=255, blank=True)
    image = models.ImageField(blank=True)

表格:

from django import forms
from django.contrib.auth.models import User
from users.models import Profile
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm

class ProfileRegistrationForm(UserCreationForm):
    username = forms.CharField(required=True, max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Enter username'}))
    email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={'placeholder': 'Enter email'}))
    password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Enter password'}), label="Password")
    password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm password'}), label="Password")

    class Meta:
        model = User
        fields = ['first_name', 'last_name','username', 'email', 'password1', 'password2']

    def save(self, commit=True):
        user = super().save(commit=False)
        user.email = self.cleaned_data['email']

        if commit: 
            user.save()

        profile = Profile(user = user, first_name = self.cleaned_data['first_name'],
                          last_name = self.cleaned_data['last_name'])

        if commit:
            profile.save()
        
        return profile
    
    def clean_username(self):
        username = self.cleaned_data['username'].lower()
        new = User.objects.filter(username=username)
        if new.count():
            raise forms.ValidationError("User already exists")
        return username
    
    def clean_email(self):
        email = self.cleaned_data['email'].lower()
        new = User.objects.filter(email=email)
        if new.count():
            raise forms.ValidationError("Email already used")
        return email
    
    def clean_password2(self):
        password1 = self.cleaned_data['password1']
        password2 = self.cleaned_data['password2']
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords doesnt match")
        return password2
    
        


class ProfileLoginForm(AuthenticationForm):
    username = forms.CharField(max_length=255, required=True)
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ['username', 'password']
    


并查看:

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .forms import ProfileLoginForm, ProfileRegistrationForm
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import AuthenticationForm



def login_user(request):
    if request.method == 'POST':
        form = AuthenticationForm(request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            return redirect('profile')
        else:
            print(form.error_messages)  
    else:
        form = ProfileLoginForm()
    return render(request, 'login.html', {'form': form})

def register(request):
    if request.method == 'POST':
        form = ProfileRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, 'Registration success')
            return redirect('login')
    else:
        form = ProfileRegistrationForm
    return render(request, 'register.html', {'form': form})

@login_required
def profile(request):
    render(request, 'profile.html', {'profile': profile})




首先我尝试使用自定义登录表单,但后来我开始使用基本的 AuthenticationForm,但仍然出现问题

python django forms model
1个回答
0
投票

分析您的文件后,发现很少有可能导致错误的问题

在您的登录视图功能中:

def login_user(request):
if request.method == 'POST':
    form = AuthenticationForm(request, data=request.POST)  # Pass the request object

在同一视图函数中替换

error_messages
并仅添加
errors

 else:
    print(form.errors)  # Show actual form errors

在注册视图函数的 else 块中添加括号

form = ProfileRegistrationForm   # wrong

form = ProfileRegistrationForm()  # right
© www.soinside.com 2019 - 2024. All rights reserved.