django Djagno Rest框架调用“User.objects.create()”时出现"类型错误“

0sgqnhkj  于 2022-12-30  发布在  Go
关注(0)|答案(2)|浏览(178)

当我尝试使用postman注册新用户时,出现以下错误:“”“调用User.objects.create()时得到TypeError。这可能是因为序列化程序类上有一个可写字段,该字段不是User.objects.create()的有效参数。您可能需要将该字段设为只读,或重写UserRegistrationSerializer。创建()方法来正确处理这个问题。“”我是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)
m0rkklqb

m0rkklqb1#

您忘记在模型中添加password和password2。在www.example.com中models.py,

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

eni9jsuy

eni9jsuy2#

请从序列化程序的create方法中删除分号,然后重试。

def create(self,validate_data):
      print(validate_data);
      return User.objects.create_user(**validate_data);  <----------

相关问题