简体   繁体   English

为什么在 django 中创建超级用户和注册创建用户有区别?

[英]Why is there a difference between creating superuser and signing up to create user in django?

I am implementing membership using django custom user model and custom register serializer.我正在使用 django 自定义用户 model 和自定义寄存器序列化程序来实现成员资格。 But when I finished the implementation and tested it, there was a little problem, so I want to ask.但是当我完成实现并测试它时,出现了一点问题,所以我想问一下。 It is the I from the console python manage.py, and when I was running a command createsuperuser sign up when to membership to access the results page with each other.它是我从控制台 python manage.py,和当我运行命令 createsuperuser 注册时以会员身份访问的结果页面。 Here are some pictures.这里有一些图片。

在此处输入图像描述

If I sign up like this,如果我这样注册,

在此处输入图像描述

password is not encrypted by pbkdf2_sha256 method, username has nothing, and profile has default_image密码没有被pbkdf2_sha256方法加密,用户名什么都没有,配置文件有default_image

在此处输入图像描述

However, the superuser created as a command in the console not only enters username and profile image normally, but password is normally encrypted in the pbkdf2_sha256 method.但是,在控制台中作为命令创建的超级用户不仅正常输入用户名和配置文件图像,而且密码通常在 pbkdf2_sha256 方法中加密。 I hope that the user who joined the signUp page will be normal user name and profile like superuser and the encryption will be the same.我希望加入注册页面的用户是普通用户名和个人资料,如超级用户,加密相同。 How can I modify my code?如何修改我的代码? Here's my code.这是我的代码。

models.py模型.py

from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin
from django.utils.translation import ugettext_lazy as _

class UserManager(BaseUserManager):
    use_in_migrations = True

    def create_user(self, email, profile, userName, password):
        user = self.create_user(
            email=self.normalize_email(email),
            password=password,
            userName=userName,
            profile=profile,
        )
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password, userName, profile):
        user = self.create_user(
            email=self.normalize_email(email),
            password=password,
            userName=userName,
            profile=profile,
        )
        user.is_staff = True
        user.is_superuser = True
        user.set_password(password)

        user.save()
        return user

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    password = models.CharField(max_length=16)
    userName = models.CharField(max_length=10)
    profile = models.ImageField(default='default_image.jpeg')
    is_staff = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

serializers.py序列化程序.py

from .models import User
from django.contrib.auth.hashers import make_password
from rest_framework import serializers
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer, TokenRefreshSerializer
from rest_framework_simplejwt.tokens import RefreshToken
from allauth.account import app_settings as allauth_settings
from allauth.utils import email_address_exists
from allauth.account.adapter import get_adapter
from allauth.account.utils import setup_user_email
from django.utils.translation import ugettext_lazy as _
from datetime import datetime, timedelta

class customRegisterSerializer (serializers.Serializer) :
    email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED)
    password = serializers.CharField(required=True, write_only=True)
    userName = serializers.CharField(required=True)
    profile = serializers.ImageField(use_url=True)

    def validate_email(self, email):
        email = get_adapter().clean_email(email)
        if allauth_settings.UNIQUE_EMAIL:
            if email and email_address_exists(email):
                raise serializers.ValidationError(
                    _("A user is already registered with this e-mail address."))
        return email

    def validate_password (self, password):
        return get_adapter().clean_password(password)

    def get_cleaned_data(self):
        return {
            'email': self.validated_data.get('email', ''),
            'password': self.validated_data.get('password', ''),
            'userName': self.validated_data.get('userName', ''),
            'profile' : self.validated_data.get('profile', ''),
        }

    def save(self, request):
        adapter = get_adapter()
        user = adapter.new_user(request)
        self.cleaned_data = self.get_cleaned_data()
        user.set_password(self.cleaned_data.get('password'))
        adapter.save_user(request, user, self)
        setup_user_email(request, user, [])
        user.save()
        return user

class customTokenObtainPairSerializer (TokenObtainPairSerializer) :
    def validate (self, attrs) :
        data = super().validate(attrs)
        refresh = self.get_token(self.user)
        del(data['refresh'])
        del(data['access'])
        data['token_type'] = 'bearer'
        data['access_token'] = str(refresh.access_token)
        data['expires_at'] = str(datetime.now() + timedelta(hours=6))
        data['refresh_token'] = str(refresh)
        data['refresh_token_expires_at'] = str(datetime.now() + timedelta(days=30))

        return data

class customTokenRefreshSerializer (TokenRefreshSerializer) :
    def validate (self, attrs) :
        data = super().validate(attrs)
        refresh = RefreshToken(attrs['refresh'])
        data['token_type'] = 'bearer'
        data['access_token'] = str(refresh.access_token)
        data['expires_at'] = str(datetime.now() + timedelta(hours=6))
        data['refresh_token'] = str(refresh)
        data['refresh_token_expires_at'] = str(datetime.now() + timedelta(days=30))
        del(data['access'])

        return data

class userProfileSerializer (serializers.ModelSerializer) :
    profile = serializers.ImageField(use_url=True)
    class Meta :
        field = ('email', 'userName', 'profile')

I also faced this error and found that due to mismatch name in template and view it return None我也遇到了这个错误,发现由于模板中的名称不匹配,查看它返回 None

create_user set password for None Trace your code **SO It got resolved in my case ** create_user 为 None 设置密码 跟踪您的代码 **所以在我的情况下它得到了解决 **

In your case use:在你的情况下使用:

def create_user(self, email, profile, userName, password):
    email=self.normalize_email(email),
    *user = self.model(email=email, **extra_fields)*
    userName=userName,
    profile=profile,
    
    user.set_password(password)
    user.save()
    return user

Instead of代替

def create_user(self, email, profile, userName, password):
    user = self.create_user(
        email=self.normalize_email(email),
        password=password,
        userName=userName,
        profile=profile,
    )
    user.set_password(password)
    user.save()
    return user

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM