Django set_password(password) 不散列密码

Django set_password(password) doesn't hash the password

在 Django 文档中,它说它对密码进行哈希处理但没有保存它,所以我必须像我一样保存它。如果我创建一个超级用户,那么一切正常,但是当我尝试创建一个用户帐户时,密码会未经散列保存到数据库中。我尝试使用 make_password,但这也不起作用,我得到了相同的结果。你有什么想法吗?

models.py

from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from datetime import datetime

from django.core.validators import MinLengthValidator

from .CHOICES import *
from django.utils.translation import gettext_lazy as _
from django.db import models

# Create your models here.
country_choice = COUNTRY_CHOICE


class CustomAccountManager(BaseUserManager):

这是自定义用户模型。

def create_superuser(self, email, username, first_name, password, **other_fields):

    other_fields.setdefault('is_staff', True)
    other_fields.setdefault('is_superuser', True)
    other_fields.setdefault('is_active', True)

    if other_fields.get('is_staff') is not True:
        raise ValueError('Superuser must be assigned to is_staff=True.')

    if other_fields.get('is_superuser') is not True:
        raise ValueError('Superuser must be assigned to is_superuser=True.')

    return self.create_user(email, username, first_name, password, **other_fields)

这是用户模型。

def create_user(self, email, username, first_name, password, **other_fields):

    if not email:
        raise ValueError(_('You must provide an email address'))

    email = self.normalize_email(email)
    user = self.model(email=email, username=username,
                      first_name=first_name, **other_fields)

    user.set_password(password)
    # user.make_password(self.request.data[password])

    user.save()
    return user


class NewUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    username = models.CharField(max_length=50, validators=[MinLengthValidator(8)], unique=True)

    first_name = models.CharField(max_length=30, validators=[MinLengthValidator(3)], blank=False)
    middle_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, validators=[MinLengthValidator(3)], blank=False)

    # date_of_birth = models.DateField(blank=True)
    # month = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(12)], blank=False)
    # year = models.IntegerField(validators=[MinValueValidator(1942), MaxValueValidator(2017)], blank=False)

    # gender model
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
        ('O', 'Other'),
    )

    gender = models.CharField(max_length=1, choices=[('M', 'Male'), ('F', 'Female'), ('O', 'Other')], blank=False)
    country = models.CharField(max_length=2, choices=COUNTRY_CHOICE, blank=False)

    datetime = models.DateTimeField(default=datetime.now())

    objects = CustomAccountManager()

    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)

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

    def __str__(self):
        return self.username

那我有forms.py

from django.forms import ModelForm, TextInput, EmailInput, PasswordInput
from .models import NewUser


class Person(ModelForm):


    class Meta:

        model = NewUser

        fields = ["username", "email", "first_name", "middle_name", "last_name",
                    "gender", "country", "password"]

和views.py

def register(request):
    if request.user.is_authenticated:
        return redirect('profiles')
    else:
        if request.method == 'POST':
            form_one = Person(request.POST)
            Person()

            if form_one.is_valid():
                form_one.save()

                username = form_one.cleaned_data.get("username")

                messages.success(request, f"Account created for {username}!")
                return redirect("login_user")

        else:
            form_one = Person()

        return render(request, "accounts/register.html", {"form_one": form_one})

我不明白怎么了。对于任何可能让您不高兴的事情,我深表歉意,我是 Django 的新手,我不能说我是 python 专家,但我会尽力而为。非常感谢您! Github link 到整个项目 https://github.com/RazzTazz28/Django-Atlas.

您必须在 set_password 之后保存用户。设置密码只会创建一个散列密码,你必须保存它

if (request.method == 'POST'):
        username = request.POST.get('username')
     
   password = request.POST.get('password') 
  user = User.objects.create_user(
            email=email,
            name=username,  
            password=password,
        )      
  user.set_password(password)
  user.save()