0

我正在使用 Djoser 创建用于用户管理的 api 端点,我想使用自定义模型来创建用户和登录,我只想使用电子邮件。

给我的用户实体没有用户名字段

下面我将分享我为我的应用程序设置的各种设置

#accounts/model.py
from django.db import models
from django.contrib.auth.models import AbstractUser

# Create your models here.

class CustomUser(AbstractUser):
    username = None
    email = models.EmailField(unique=True)
    REQUIRED_FIELDS = ['first_name', 'last_name']
    USERNAME_FIELD = 'email'

    def __str__(self):
        return self.email

我的序列化程序文件

#accounts/serializers.py
from djoser.serializers import UserCreateSerializer, UserSerializer
from rest_framework import serializers
from rest_framework.fields import CurrentUserDefault
from .models import CustomUser

class UserCreateSerializer(UserCreateSerializer):
    class Meta:
        model = CustomUser
        fields = ['id', 'email', 'first_name', 'last_name']

#settings.py
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        # 'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.TokenAuthentication',

    ),
    'DEFAULT_PERMISSIONS_CLASSES': (
        'rest_framework.permissions.IsAuthenticated'
    )
}

AUTH_USER_MODEL = 'accounts.CustomUser'

DJOSER = {
    'LOGIN_FIELD': 'email',
    'USER_CREATE_PASSWORD_RETYPE': True,
    'SERIALIZERS': {
        'user_create': 'accounts.serializers.UserCreateSerializer',
        'user': 'accounts.serializers.UserCreateSerializer',
        # 'current_user': 'accounts.serializers.CurrentUserSerializer'
    }

当我尝试注册用户时,我得到

TypeError at /auth/users/

create_user() missing 1 required positional argument: 'username'

Request Method:     POST
Request URL:    http://127.0.0.1:8000/auth/users/
Django Version:     3.1
Exception Type:     TypeError
Exception Value:    

create_user() missing 1 required positional argument: 'username'

Exception Location:     /home/femiir/.virtualenvs/codegarage/lib/python3.8/site-packages/djoser/serializers.py, line 73, in perform_create
Python Executable:  /home/femiir/.virtualenvs/codegarage/bin/python
Python Version:     3.8.5

请问我做错了什么?

4

1 回答 1

1

您需要有一个自定义用户管理器,可能是这样的:

from django.contrib.auth.base_user import BaseUserManager


class MyUserManager(BaseUserManager):
    def create_user(self, email, password=None, **extra_fields):
        """
        Creates and saves a User with the given email, first name,
        last name and password.
        """
        if not email:
            raise ValueError("Users must have an email address")

        user = self.model(
            email=self.normalize_email(email),
            **extra_fields,
        )

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

    def create_superuser(self, email, password=None, **extra_fields):
        """
        Creates and saves a superuser with the given email, first name,
        last name and password.
        """
        user = self.create_user(
            email,
            password=password,
            **extra_fields,
        )
        user.is_admin = True
        user.save(using=self._db)
        return user

在您的自定义用户模型中:

class CustomUser(AbstractBaseUser):
    # [...]
    objects = MyUserManager()
    # [...]

我从 django 文档中获取了关于自定义用户模型的代码。他们提供了一个使用电子邮件作为用户名字段的示例(这是您想要的)。

您可以保留 from 的继承,AbstractUser但如果您不需要该模型中的大部分内容,您也可以从 继承您的模型AbstractBaseUser,如示例中所示。

于 2021-04-24T22:44:42.457 回答