Djagno Rest Framework 调用 `User.objects.create()` 时出现 `TypeError`

问题描述 投票:0回答:2

当我尝试使用邮递员注册新用户时,出现以下错误: ''' 拨打

TypeError
时收到
User.objects.create()
。这可能是因为序列化器类上有一个可写字段,该字段不是
User.objects.create()
的有效参数。您可能需要将该字段设置为只读,或者重写 UserRegistrationSerializer.create() 方法才能正确处理此问题。 ''' 我是 Django 和 DRF 的新手,并且已经在这个问题上停留了几个小时,谁能解释一下是什么产生了这个错误。我一直在关注教程,相同的代码对他也适用。

序列化器。 py

from rest_framework import serializers
from account.models import User

class UserRegistrationSerializer(serializers.ModelSerializer):
  password2 = serializers.CharField(style={'input_type':'password'},write_only=True)
  class  Meta:
    model =  User
    fields = ['email','name','password','password2','tc']
    extra_kwargs = {
      'password':{'write_only':True}
    }
    # validating Password and confirm password while Registration
    def validate(self,attrs):
      password = attrs.get('password')
      password2 = attrs.get('password2')
      if password != password2:
        raise serializers.ValidationError("Password and confirm password doesn't match")
      return attrs
    
    def create(self,validate_data):
      print(validate_data);
      return User.objects.create_user(**validate_data);
    
    

模型.py

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

# Custom User Manager
class UserManager(BaseUserManager):
  def create_user(self, email, name,tc, password=None,password2=None):
      """
      Creates and saves a User with the given email, name, tc and password.
      """
      if not email:
          raise ValueError('Users must have an email address')

      user = self.model(
          email=self.normalize_email(email),
          name = name,
          tc = tc,
      )

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

  def create_superuser(self, email, name,tc, password=None):
      """
      Creates and saves a superuser with the given email, name, tc and password.
      """
      user = self.create_user(
          email,
          password=password,
          name=name,
          tc=tc,
      )
      user.is_admin = True
      user.save(using=self._db)
      return user
# Custom user model
class User(AbstractBaseUser):
  email = models.EmailField(
      verbose_name='Email',
      max_length=255,
      unique=True,
  )
  name = models.CharField(max_length=200)
  tc = models.BooleanField()
  is_active = models.BooleanField(default=True)
  is_admin = models.BooleanField(default=False)
  created_at = models.DateTimeField(auto_now_add=True)
  updated_at = models.DateTimeField(auto_now=True)
  
  objects = UserManager()

  USERNAME_FIELD = 'email'
  REQUIRED_FIELDS = ['name','tc']

  def __str__(self):
      return self.email

  def has_perm(self, perm, obj=None):
      "Does the user have a specific permission?"
      # Simplest possible answer: Yes, always
      return self.is_admin

  def has_module_perms(self, app_label):
      "Does the user have permissions to view the app `app_label`?"
      # Simplest possible answer: Yes, always
      return True

  @property
  def is_staff(self):
      "Is the user a member of staff?"
      # Simplest possible answer: All admins are staff
      return self.is_admin

views.py

from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
from account.serializers import UserRegistrationSerializer
class UserRegistrationView(APIView):
  def post(self,request,format=None):
    serializer = UserRegistrationSerializer( data = request.data);
    print("******************************************")
    print(request.data);
    if serializer.is_valid(raise_exception=True):
      user = serializer.save()
      return Response({'msg':'Registration Sucssess'},status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  
  

django django-rest-framework django-rest-auth
2个回答
0
投票

您忘记在模型中添加密码和密码2。 在 models.py 中,

class User(AbstractBaseUser):
   password = models.Charfield(max_length=255)
   password2 = models.Charfield(max_length=255)


0
投票

您的问题最终找到解决方案了吗?我也遇到同样的问题。

© www.soinside.com 2019 - 2024. All rights reserved.