使用AbstractBaseUser和BaseUserManager在Django RestFramework中定制模型。

huangapple go评论73阅读模式
英文:

customize models in Django RestFramework using AbstractBaseUser, BaseUserManager

问题

我想自定义模型,所以我使用了AbstractBaseUser和BaseUserManager。我使用**extra_field来添加'point'属性。

我访问了http://127.0.0.1:8000/account/signup/并输入了我的数据,但出现了错误。

我的代码有什么问题?我是初学者,请帮帮我。

英文:

i wanna customize models. so i used AbstractBaseUser, BaseUserManager
i use **extra_field to add 'point' attribute.

i enterd http://127.0.0.1:8000/account/signup/
and write my data
but the errors occured

enter image description here

what's wrong with my code?
i'm a beginner, plz help me

# serializers.py

from .models import User
from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):
    def create(self, validated_data):
        user = User.objects.create_user(
            email = validated_data['email'],
            nickname = validated_data['nickname'],
            name = validated_data['name'],
            password = validated_data['password'],
            point = validated_data['point']
        )
        return user
    class Meta:
        model = User
        fields = ['name', 'nickname', 'email', 'password']


# models.py

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager

class UserManager(BaseUserManager):

    def create_user(self, email, nickname, name, password=None, **point):
        if not email:
            raise ValueError('must have user email')
        if not nickname:
            raise ValueError('must have user nickname')
        if not name:
            raise ValueError('must have user name')
        user = self.model(
            email = self.normalize_email(email),
            nickname = nickname,
            name = name,
            point = point
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, nickname, name, password=None):
        user = self.create_user(
            email,
            password = password,
            nickname = nickname,
            name = name
        )
        user.is_admin = True
        user.save(using=self._db)
        return user

class User(AbstractBaseUser):
    id = models.AutoField(primary_key=True)
    email = models.EmailField(default='', max_length=100, null=False, blank=False, unique=True)
    nickname = models.CharField(default='', max_length=100, null=False, blank=False, unique=False)
    name = models.CharField(default='', max_length=100, null=False, blank=False)
    point = models.IntegerField(default=500, max_length=10000000)

    is_active = models.BooleanField(default=True)    
    is_admin = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'

    REQUIRED_FIELDS = ['email', 'name', 'nickname', 'password']

    def __str__(self):
        return self.name

# views.py

from django.shortcuts import render
from .serializers import UserSerializer
from .models import User
from rest_framework import generics

# 회원가입
class UserCreate(generics.CreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
# urls.py

from django.urls import path, include
from . import views
from rest_framework import urls

urlpatterns =[
    path('signup/', views.UserCreate.as_view()),
    path('api-auth/', include('rest_framework.urls')),
 ]

i wanna customize models. so i used AbstractBaseUser, BaseUserManager
i use **extra_field to add 'point' attribute.

i enterd http://127.0.0.1:8000/account/signup/
and write my data
but the errors occured

what's wrong with my code?
i'm a beginner, plz help me

答案1

得分: 0

当你使用 ** 解包值时,你应该这样访问这些值:

def create_user(self, email, nickname, name, password=None, **kwargs):
        if not email:
            raise ValueError('必须提供用户邮箱')
        if not nickname:
            raise ValueError('必须提供用户昵称')
        if not name:
            raise ValueError('必须提供用户姓名')
        user = self.model(
            email = self.normalize_email(email),
            nickname = nickname,
            name = name,
            point = kwargs['point']
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

注意我如何获取 point 的值。问题在于你对 point 的定义是 { point: 500 }。所以它是一个字典。你需要从该字典中获取 point 的值。

英文:

When you unpack values using ** then you should access the values like this:

def create_user(self, email, nickname, name, password=None, **kwargs):
        if not email:
            raise ValueError('must have user email')
        if not nickname:
            raise ValueError('must have user nickname')
        if not name:
            raise ValueError('must have user name')
        user = self.model(
            email = self.normalize_email(email),
            nickname = nickname,
            name = name,
            point = kwargs['point']
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

Check how I get the value of point. The thing is that your definition of point is { point: 500 }. So is a dict. You need to get the value of point from that dict.

huangapple
  • 本文由 发表于 2023年2月13日 23:49:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75438186.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定