简体   繁体   English

Django不在用户模型中存储密码字段

[英]Django doesn't store password field in User model

I created a signup page using Django's builtin signup forms.Here is my code below 我使用Django的内置注册表单创建了注册页面,这是下面的代码

forms.py 表格

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User


class SignUpForm(UserCreationForm):
    email = forms.EmailField(max_length=254, help_text='Please provide a valid email address.')
    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')

    def clean(self):
        cleaned_data = super(SignUpForm, self).clean()
        username = cleaned_data.get("username")
        email = cleaned_data.get("email")


        check_email = User.objects.filter(email=email)
        if check_email:
            raise forms.ValidationError(
                "You are already registered!")
            return cleaned_data

        check_username = User.objects.filter(username=username)
        if check_username:
            raise forms.ValidationError(
                "A user with that username already exists")
            return cleaned_data

In my views.py this is how I do the authentication for signup 在我的views.py中,这就是我进行注册身份验证的方式

views.py views.py

@csrf_exempt
def signup_users(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            print("signup authencticate", user)
            login(request, user)
            return redirect('/')
    else:
        form = SignUpForm()
    return render(request, 'signup.html', {'form': form})

Here is my code to handle user login 这是我处理用户登录的代码

@csrf_exempt
def login_view(request):
    print(request.user.is_authenticated())
    if request.POST:
        email = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(email=email, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/')
        else:
            return render(request, "login.html")   

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

When I signup, everything seems fine but when I try to login, it just won't let me login. 当我注册时,一切似乎都很好,但是当我尝试登录时,它只是不允许我登录。

So when I checked the django admin , this is what I found 所以当我检查django admin ,这就是我发现的

Username: tech1
Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.
Password:
Invalid password format or unknown hashing algorithm.
Raw passwords are not stored, so there is no way to see this user's password, but you can change the password using this form.

I don't quite understand why the user password is not stored at the time of signup? 我不太了解为什么在注册时未存储用户密码?

I searched for it and I found out from this answer using User.objects.get_or_create() gives invalid password format in django? 我进行了搜索,并使用User.objects.get_or_create()从此答案中找到了在django中提供无效密码格式的信息? that django encrypts the password before storing and I should use something like django在存储之前对密码进行了加密,我应该使用类似

user, created = User.objects.get_or_create(username="testuser2")
user.set_password('123')

But I am not quite sure where to put this in my code or how does this help?What is going on? 但是我不确定在代码中的什么地方或这有什么帮助?发生了什么?

Here basics of how I set up a custom user model: 以下是我如何设置自定义用户模型的基础知识:

In Settings.py add: 在Settings.py中添加:

AUTH_USER_MODEL = "accounts.User"

accounts can be where ever you store you user model. 帐户可以是存储用户模型的任何地方。

User model: 用户模型:

from django.contrib.auth.models import (
    AbstractBaseUser,
    BaseUserManager,
    PermissionsMixin
)
from django.conf import settings
from django.db import models
from django.utils import timezone
import binascii
import os



class UserManager(BaseUserManager):
    def create_user(self, email, first_name, last_name, password):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')


        user = self.model.objects.create(
            email=self.normalize_email(email),
            first_name = first_name,
            last_name = last_name,
        )

        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, first_name, last_name, password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(
            email,
            first_name,
            last_name,
            password
        )
        user.is_superuser = True
        user.save()
        return user


class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    first_name = models.CharField(max_length=40, null=True, blank=True)
    last_name = models.CharField(max_length=140, null=True, blank=True)
    date_joined = models.DateTimeField(default=timezone.now)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name']


    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.first_name

    def __str__(self):              # __unicode__ on Python 2
        return self.first_name

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_superuser

I can not recall but I am pretty sure the manager must come first. 我不记得了,但我很确定经理必须先行。

Signup 注册

class SignUp(generic.CreateView):
    form_class = forms.UserCreateForm
    success_url = "accounts/pre/"
    template_name = "accounts/signup.html"
    def form_valid(self, form):
        valid = super(SignUp, self).form_valid(form)
        email, password = form.cleaned_data.get('email'), form.cleaned_data.get('password1')
        new_user = authenticate(email=email, password=password)
        auth_login(self.request, new_user)
        return valid

Forms.py Forms.py

class UserCreateForm(UserCreationForm):
    class Meta:
        fields = ("email", "password1", "password2", "first_name", "last_name")
        model = get_user_model()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["email"].widget.attrs.update({'class': 'form-control', 'placeholder': 'Email'})
        self.fields["first_name"].widget.attrs.update({'class': 'form-control', 'placeholder': 'First Name'})
        self.fields["last_name"].widget.attrs.update({'class': 'form-control', 'placeholder': 'Last Name'})
        self.fields["password1"].widget.attrs.update({'class': 'form-control', 'placeholder': 'Password'})
        self.fields["password2"].widget.attrs.update({'class': 'form-control', 'placeholder': 'Reenter Password'})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Hash 用户之外的密码字段 model - Django - Hash a password field outside of the User model - Django 省略自定义 django 用户模型的密码字段 - Omitting password field for custom django user model Django:如何在不更新用户密码字段的情况下更新用户模型 - Django: How to update user model without updating user password field Django model 字段与其他不存在的 model 字段冲突? - Django model field clashes with other model field that doesn't exist? Django自定义用户模型密码字段显示纯文本 - Django customize user model Password field showing plain text 无法使用 ModelViewSet 更改 Django 用户模型的用户密码 - Can't change user password for Django user model using ModelViewSet Django ValueError:字段 admin.LogEntry.user 被声明为对“app.user”的惰性引用,但应用“app”不提供模型“用户” - Django ValueError: field admin.LogEntry.user was declared with a lazy reference to 'app.user', but app 'app' doesn't provide model 'user' 为什么我的 Django 用户模型的密码没有经过哈希处理? - Why isn't my Django User Model's Password Hashed? 在Django Admin中更改自定义用户模型时,使用纯文本字段而不是特殊密码字段? - When changing a Custom User model in Django Admin a plain text field is used instead of the special password field? django-在查询集中的字段中添加模型中不存在的字段 - django - prepending a field in the query set that doesn't exist in the model
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM