Home > Mobile >  Djagno Rest Framework Got a `TypeError` when calling `User.objects.create()`
Djagno Rest Framework Got a `TypeError` when calling `User.objects.create()`

Time:12-29

When I am trying to register new user using postman I get the following error: ''' Got a TypeError when calling User.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to User.objects.create(). You may need to make the field read-only, or override the UserRegistrationSerializer.create() method to handle this correctly. ''' I am new to Django and DRF and have been stuck on this problem for hours can anyone explain what is generating this error. I have been following tutorial and same code works for him.

serializers. 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);
    
    

Models .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)
  
  

CodePudding user response:

You have forgotten to add password and password2 in the models. In models.py,

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

CodePudding user response:

remove semicolon from the create method in serializer and try again.

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