我不确定为什么使用Django Rest Framework创建新的自定义用户(作为用户名的电子邮件)时不对我的密码进行哈希处理
这就是我在postgres中看到的。不确定为什么即使迁移后我的admin / staff / active列也没有显示
models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, password=None, first_name=None, last_name=None, is_active=True, is_staff=False, is_admin=False):
if not email or not first_name or not last_name:
raise ValueError('Email is required')
if not password:
raise ValueError('Password is required')
if not first_name:
raise ValueError('First name is required')
if not last_name:
raise ValueError('Last name is required')
user_object = self.model(
email=self.normalize_email(email),
first_name=first_name,
last_name=last_name,
active=is_active,
staff=is_staff,
admin=is_admin,
)
user_object.set_password(password) # change password
user_object.save(self._db)
return user_object
def create_staff_user(self, email, first_name, last_name, password=None):
staff_user_object = self.create_user(email, first_name, last_name, password, is_staff=True)
return staff_user_object
def create_superuser(self, email, first_name, last_name, password=None):
super_user_object = self.create_user(email, first_name, last_name, password, is_staff=True, is_admin=True)
return super_user_object
class User(AbstractBaseUser):
email = models.EmailField(unique=True, max_length=255)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
date_joined = models.DateTimeField(auto_now_add=True) # joined timestamp
is_active = models.BooleanField(default=True) # Can login?
is_staff = models.BooleanField(default=False) # staff user, non super user
is_admin = models.BooleanField(default=False) # super user?
objects = UserManager()
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = [] # email and passwords are required by default
settings.py
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', # Using Bcrypt to store passwords
views.py
class UserList(generics.ListCreateAPIView):
""" List all Users, or create a new User. """
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveUpdateDestroyAPIView):
""" Retrieve, update or delete a User instance. """
queryset = User.objects.all()
serializer_class = UserSerializer
]
urls.py
urlpatterns = [
path('accounts/', views.UserList.as_view()),
path('accounts/<int:pk>/', views.UserDetail.as_view()),
]
序列化器
from rest_framework import serializers
from .models import User
from properties.models import Property
class UserSerializer(serializers.ModelSerializer):
properties = serializers.PrimaryKeyRelatedField(many=True, queryset=Property.objects.all())
class Meta:
model = User
fields = '__all__'
参考方案
DRF序列化程序调用模型的默认create()
方法,而不会调用.set_password()
方法。因此,您必须在UserSerializer的create()方法中显式调用该方法
class UserSerializer(serializers.ModelSerializer):
# other code
def create(self, validated_data):
password = validated_data.pop('password', None)
user_instance = super().create(validated_data)
if password:
user_instance.set_password(password)
user_instance.save()
return user_instance
Python sqlite3数据库已锁定 - python我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…
处理后如何删除照片? - python我的Django模型中有两个字段: class Staff(models.Model): photo = models.FileField(blank=True, null = True) encodings = JSONField() 我从表单获取照片,然后使用该照片获取编码。处理后如何删除照片?我试过了self.photo = None or self.…
django-compressor未与django-shop一起安装 - python我无法使用django-shop安装django-compressor。出现这样的错误。Failed building wheel for rcssmin ================================= Failed building wheel for rjsmin -----------------------------------…
如何从func1中获取var1并在func2中使用它,而又不会在func1中运行两次 - python我有一个包含变量的func1,我想在func2中访问该变量。我尝试在下面的代码中返回func1中的变量,然后将变量"user_name"设置为函数"first_name_information",但这会使func1运行两次,我不想发生这种情况。def func1(): user_name = input("W…
如何在Django中解决模块名称冲突? - python创建Django应用程序时出错:python端发生错误。退出代码:1,err:CommandError:'untitled1'与现有Python模块的名称冲突,因此不能用作项目名称。请尝试使用其他名称。 python大神给出的解决方案 您正在使用哪个版本的python?升级您的django版本或降级您的python版本,这应该可以解决问题。您可以在cl中执行…