使用自定义模型 fo django djoser

using custom model fo django djoser

我正在使用 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

请问我做错了什么?

你需要有一个自定义用户管理器,大概是这样的:

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 文档中获取了有关自定义用户模型的代码。他们提供an example using the email as the username field(这就是你想要的)。

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