在我的django authenticationform中,用户名和密码总是不正确

发布于 2025-02-10 13:06:43 字数 2450 浏览 2 评论 0 原文

我正在尝试通过用户名和密码登录用户,但是当我尝试检查form.is_valid()时,它会返回false。错误列表包含错误:“请输入正确的用户名和密码。请注意,这两个字段都可能对大小写。”。当我不指定自己的帖子时,它也行不通。

我一直在寻找错字,但没有找到。在互联网中,没有任何帮助。 我尝试了开关表格和字段,但是错误是相同的。

views.py:

from django.views.generic import *
from django.views.generic import *
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import authenticate, login, logout

...
class RegisterView(CreateView):
    form_class = UserRegisterForm
    success_url = reverse_lazy('main:homepage')
    template_name = "accounts/register.html"

    def post(self, request):
        form = self.get_form()
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect("main:homepage")
        else:
            print(form.errors)
            return redirect("accounts:register")

class LoginView(FormView):
    form_class = AuthenticationForm
    template_name = "accounts/login.html"

    def post(self, request):
        form = self.get_form()
        if form.is_valid():
            form.clean()
            user = authenticate(
                request, 
                username=form.cleaned_data["username"], 
                password=form.cleaned_data["password"],
            )
            login(request, user)
            return redirect("main:homepage")
        else:
            print(form.errors)
            print(form.cleaned_data)
            
            return redirect("accounts:login")

forms.py:

from django import forms
from django.contrib.auth import get_user_model, authenticate, login
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = get_user_model()
        fields = ['username', 'email', 'first_name']


    def save(self):
        self.clean()
        user = self.Meta.model(
            username = self.cleaned_data['username'], 
            email = self.cleaned_data['email'], 
            password = self.cleaned_data['password2'], 
        )
        user.save()
        return user

login.html:

<div class="wrap">
    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">CONFIRM LOGIN</button>
    </form>
</div>

I'm trying to login user by his username and password, but when i'm trying to check form.is_valid(), it returns False. Errorlist contain error: "Please enter a correct username and password. Note that both fields may be case-sensitive.". When i don't specify my own post it's doesn't work either.

I was looking for typo, but didn't found any. In internet nothing helped me at all.
I tried switch form and it's fields, but error was the same.

views.py:

from django.views.generic import *
from django.views.generic import *
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import authenticate, login, logout

...
class RegisterView(CreateView):
    form_class = UserRegisterForm
    success_url = reverse_lazy('main:homepage')
    template_name = "accounts/register.html"

    def post(self, request):
        form = self.get_form()
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect("main:homepage")
        else:
            print(form.errors)
            return redirect("accounts:register")

class LoginView(FormView):
    form_class = AuthenticationForm
    template_name = "accounts/login.html"

    def post(self, request):
        form = self.get_form()
        if form.is_valid():
            form.clean()
            user = authenticate(
                request, 
                username=form.cleaned_data["username"], 
                password=form.cleaned_data["password"],
            )
            login(request, user)
            return redirect("main:homepage")
        else:
            print(form.errors)
            print(form.cleaned_data)
            
            return redirect("accounts:login")

forms.py:

from django import forms
from django.contrib.auth import get_user_model, authenticate, login
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = get_user_model()
        fields = ['username', 'email', 'first_name']


    def save(self):
        self.clean()
        user = self.Meta.model(
            username = self.cleaned_data['username'], 
            email = self.cleaned_data['email'], 
            password = self.cleaned_data['password2'], 
        )
        user.save()
        return user

login.html:

<div class="wrap">
    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">CONFIRM LOGIN</button>
    </form>
</div>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

可遇━不可求 2025-02-17 13:06:43

您的代码片段都是正确的,但是保存用户密码的方法在从Via Save方法中,保存密码的方式不正确,如果您想检查密码,它将密码的原始文本形式保存到数据库中。 ,只需打开您的数据库并检查密码字段,它们以原始文本格式存储(Exapmle:testing123),其中Django保存,检索,使用密码的SHA256的密码,直到和除非您没有指定它,否则PBKDF2_SHA256 ...这种格式。

不要这样的用户:

user = User(username = username , password = password , email = email)
user.save()

像这样

user = User(username = username , email = email)
user.set_password(password)
user.save()

更新您的代码段:

from django import forms
from django.contrib.auth import get_user_model, authenticate, login
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = get_user_model()
        fields = ['username', 'email', 'first_name']


    def save(self):
        self.clean()
        user = self.Meta.model(
            username = self.cleaned_data['username'], 
            email = self.cleaned_data['email'], 
        )
        user.set_password(self.cleaned_data['password2'])
        user.save()
        return user

这将完成所需的工作。

Your code snippets are all correct , but the way of saving the user's password is incorrect in the from via save method , the way you are saving the password , it saves the raw text form of the password to the database , if you want to check , just open your database and check the password fields , they are stored in raw text format ( exapmle : testing123) where as the django saves , retrieves , password using password hashing alogrithm of sha256 until and unless you have not specified it and its hashes to pbkdf2_sha256... this format .

dont save user like this :

user = User(username = username , password = password , email = email)
user.save()

save like this

user = User(username = username , email = email)
user.set_password(password)
user.save()

Update your code snippet :

from django import forms
from django.contrib.auth import get_user_model, authenticate, login
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = get_user_model()
        fields = ['username', 'email', 'first_name']


    def save(self):
        self.clean()
        user = self.Meta.model(
            username = self.cleaned_data['username'], 
            email = self.cleaned_data['email'], 
        )
        user.set_password(self.cleaned_data['password2'])
        user.save()
        return user

This will do the required work.

陌上芳菲 2025-02-17 13:06:43
class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = get_user_model()
        fields = ['username', 'email', 'first_name']


    def save(self):
        self.clean()
        user = self.Meta.model(
            username = self.cleaned_data['username'], 
            email = self.cleaned_data['email'], 
        )
        # Set password with method is solution
        user.set_password(self.cleaned_data['password2']) 
        user.save()
        return user
class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = get_user_model()
        fields = ['username', 'email', 'first_name']


    def save(self):
        self.clean()
        user = self.Meta.model(
            username = self.cleaned_data['username'], 
            email = self.cleaned_data['email'], 
        )
        # Set password with method is solution
        user.set_password(self.cleaned_data['password2']) 
        user.save()
        return user
待天淡蓝洁白时 2025-02-17 13:06:43

之所以没有起作用,是因为密码是 hashed ,并且您的 userRegisterform 无法正确放置密码。但是,无需覆盖 .save(…)方法。 django's &nbsp; [django-doc] 已经正确处理了这一点,因为它是 modelform &nbsp; [django-- doc] ,所以:

from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = get_user_model()
        fields = ['username', 'email', 'first_name']
    
    # no override of save

The reason this does not work is because passwords are hashed, and your UserRegisterForm does not hash the password properly. There is however no need to override the .save(…) method. Django's UserCreationForm [Django-doc] already takes care of this properly, since it is a ModelForm [Django-doc], so:

from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = get_user_model()
        fields = ['username', 'email', 'first_name']
    
    # no override of save
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文