Django-rest-auth(dj-rest-auth)自定义用户注册

7fyelxc5  于 2023-06-25  发布在  Go
关注(0)|答案(3)|浏览(144)

我正在使用dj-rest-auth(https://dj-rest-auth.readthedocs.io/en/latest/)并尝试实现自定义注册表单。当我尝试注册一个新用户时,我有基本表单。我在旧版本(https://django-rest-auth.readthedocs.io/en/latest/)中看到,如果您使用password 1和password 2,则不必重新键入所有代码。
serializers.py

from rest_framework import serializers
from dj_rest_auth.registration.serializers import RegisterSerializer

class CustomRegisterSerializer(RegisterSerializer):
    first_name = serializers.CharField()
    last_name = serializers.CharField()

    def get_cleaned_data(self):
        super(CustomRegisterSerializer, self).get_cleaned_data()
        return {
            'username': self.validated_data.get('username', ''),
            'password1': self.validated_data.get('password1', ''),
            'password2': self.validated_data.get('password2', ''),
            'email': self.validated_data.get('email', ''),
            'first_name': self.validated_data.get('first_name', ''),
            'last_name': self.validated_data.get('last_name', '')
        }

settings.py

REST_AUTH_SERIALIZERS = {
    'REGISTER_SERIALIZER': 'accounts.serializers.CustomRegisterSerializer',
}
cwtwac6a

cwtwac6a1#

问题出在settings.py:

REST_AUTH_REGISTER_SERIALIZERS = {
    'REGISTER_SERIALIZER': 'accounts.serializers.CustomRegisterSerializer'
}
juzqafwq

juzqafwq2#

您可以创建自己的User,并将其作为项目的AUTH_USER_MODEL,方法如下:

from django.contrib.auth.models import AbstractUser, BaseUserManager

class MyUserManager(BaseUserManager):
    def create_user(self, email, username,first_name, last_name, password=None):
        user = self.model(
            email=self.normalize_email(email),
            username=username,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self,email, username, password, first_name, last_name, is_tutor, is_student):
        user = self.create_user(
            email=self.normalize_email(email),
            username=username,
            password=password,
            first_name=first_name,
            last_name=last_name,
        )

        user.is_staff = True
        user.is_admin = True
        user.is_superuser = True
        user.save(using=self._db)
        return user

class User(AbstractBaseUser):
    email =             models.EmailField(verbose_name='email', max_length=60, unique=True)
    username =          models.CharField(max_length=30, unique=True)
    date_joined =       models.DateField(verbose_name='date joined', auto_now_add=True)
    last_login =        models.DateField(verbose_name='last login', auto_now=True)
    is_admin =          models.BooleanField(default=False)
    is_active =         models.BooleanField(default=True)
    is_staff =          models.BooleanField(default=False)
    is_superuser =      models.BooleanField(default=False)
    rating =            models.FloatField(default=0, blank=True, null=True)
    reviews_count =     models.IntegerField(default=0)
    first_name =        models.CharField(verbose_name='first_name', max_length=30)
    last_name =         models.CharField(verbose_name='last_name', max_length=30)

    USERNAME_FIELD = 'email' 
#this field means that when you try to sign in the username field will be the email 
#change it to whatever you want django to see as the username when authenticating the user
    REQUIRED_FIELDS = ['username', 'first_name', 'last_name',]

    objects = MyUserManager()

    def __str__(self):
        return self.first_name + ' - ' + self.email

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True

然后在www.example.com中settings.py声明AUTH_USER_MODEL =“to the model you just created”,并在www.example.com中serializers.py为用户注册创建一个序列化器:

class UserRegistrationSerializer(serializers.ModelSerializer):

    password2 = serializers.CharField(style={'input_type':'password'}, write_only=True)

    class Meta:
        model = User
        fields = ['username', 'email', 'first_name','last_name',
        'password', 'password2',]
        extra_kwargs = {
            'password': {
                'write_only':True
            }
        }

    def save(self):
        user = User(
            email=self.validated_data['email'],
            username=self.validated_data['username'],
            first_name=self.validated_data['first_name'],
            last_name=self.validated_data['last_name'],
            is_tutor=self.validated_data['is_tutor'],
            is_student=self.validated_data['is_student'],
        )

        password = self.validated_data['password']
        password2 = self.validated_data['password2']

        if password != password2:
            raise serializers.ValidationError({'password':'Passwords must match.'})
        user.set_password(password)
        user.save()
        return user

然后在django admin中注册自定义用户模型

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

class AccountAdmin(UserAdmin):
    list_display = ('email', 'username','pk', 'date_joined', 'last_login', 'is_admin', 'is_staff')
    search_fields = ('email', 'username')
    readonly_fields = ('date_joined', 'last_login')

    filter_horizontal = ()
    list_filter = ()
    fieldsets = ()

admin.site.register(User, AccountAdmin)

我希望这对你有帮助或者至少能为你指明正确的方向,让你达到你想要达到的目标

os8fio9y

os8fio9y3#

现在它应该在www.example.com中的REST_AUTH对象中settings.py:

REST_AUTH = {
   "REGISTER_SERIALIZER":"users.api.serializers.CusomRegisterSerializer"
}

相关问题