我正在尝试使用djoser实现身份验证。由于我在项目开始时没有扩展我AbstractBaseUser
的 from Django
,我决定使用一对一的配置文件关系模式。我有一个单独的用户应用程序,这是我的相关代码:
# models.py (user and profile models)
from django.db import models
# Create your models here.
from django.db import models
from django.contrib.auth.models import User as BaseUser
class User(BaseUser):
@property
def mobile_number(self):
return self.profile.mobile_number
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
mobile_number = models.CharField(max_length=11, unique=True)
def __str__(self):
return self.user.username
# settings.py (djoser settings)
...
DJOSER = {
"SERIALIZERS":{
"user": "user.serializers.UserSerializer"
"current_user": "user.serializers.UserSerializer"
"user_create": "user.serializers.UserCreateSerializer"
}
...
}
...
# user.serializers.py
from rest_framework import serializers
from .models import UserProfile
from .models import User
from djoser.serializers import UserCreateSerializer as BaseUserCreateSerializer
from djoser.serializers import UserSerializer as BaseUserSerializer
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
exclude = ["user"]
class UserSerializer(serializers.ModelSerializer):
mobile_number = serializers.CharField(required=True, allow_blank=False)
class Meta:
model = User
fields = ["username", "email", "first_name", "last_name", "mobile_number"]
class UserCreateSerializer(BaseUserCreateSerializer):
mobile_number = serializers.CharField(required=True, allow_blank=False)
class Meta(BaseUserCreateSerializer.Meta):
fields = ["username", "email", "first_name", "last_name", "mobile_number"]
def create(self, validated_data):
mobile_number = validated_data.pop("mobile_number")
user = super.create(**validated_data)
UserProfile.objects.create(user=user, mobile_number=mobile_number)
return user
我在这里想做的是
django
User
只需向模型添加一个属性即可跳过迁移。- 扩展 Djoser 序列化程序以仅在创建步骤中创建关系。
但是当我尝试使用djoser endpoint (auth/users/create)
这样的主体创建具有发布请求的用户时:
{
"username": "user",
"email": "user@examssple.com",
"first_name": "hatef",
"last_name": "madani",
"mobile_number": "01236549879"
}
我收到此错误:"User() got an unexpected keyword argument 'mobile_number'"
。对当前方法或更好方法的任何帮助都会很棒。