TypeError: User() got unexpected keyword arguments: 'password2' : Django JWT Authentication

Question:

I am trying to build a user authentication app using django JWT token, when i try to test my user authentication api and validate the password and password2 , it generate the following error:

TypeError: User() got unexpected keyword arguments: 'password2'

My serializers.py is as follows:

from rest_framework import serializers
from account.models import User

class UserRegistrationSerializers(serializers.ModelSerializer):
    password2=serializers.CharField(style={'input_type':'password'}, write_only=True)
    class Meta:
        model = User
        fields=['email','name','tc','password','password2']
        extra_kwargs={
            'password':{'write_only':True}
        }

def validate(self, attrs):
    password=attrs.get('password')
    password2=attrs.get('password2')
    if password != password2:
        raise serializer.ValidationError("Password and Confirm Password Does not match")
    return attrs

def validate_data(self, validate_data):
    return User.objects.create_user(**validate_data)

and my views.py is as follows:

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
from account.serializers import UserRegistrationSerializers


# Create your views here.
class UserRegistrationView(APIView):
    def post(self, request, format=None):
        serializer=  UserRegistrationSerializers(data=request.data)
        if serializer.is_valid(raise_exception=True):
            user= serializer.save()
            return Response({'msg':'Registration Successful'}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 

my models.py file is as follows:

from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
# Create your models here.

class UserManager(BaseUserManager):
    def create_user(self, email, name, tc, password=None, password2=None):
        """
        Creates and saves a User with the given email, date of
        birth 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, date of
        birth and password.
        """
        user = self.create_user(
            email,
            password=password,
            name=name,
            tc=tc,
        )
        user.is_admin = True
        user.save(using=self._db)
        return user
class User(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='Email',
        max_length=255,
        unique=True,
    )
    #date_of_birth = models.DateField()
    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

The full traceback is as follows:

Traceback (most recent call last): File
"D:jwtlibsite-packagesdjangocorehandlersexception.py", line 55,
in inner
response = get_response(request) File "D:jwtlibsite-packagesdjangocorehandlersbase.py", line 197, in
_get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:jwtlibsite-packagesdjangoviewsdecoratorscsrf.py", line 54,
in wrapped_view
return view_func(*args, **kwargs) File "D:jwtlibsite-packagesdjangoviewsgenericbase.py", line 103, in
view
return self.dispatch(request, *args, **kwargs) File "D:jwtlibsite-packagesrest_frameworkviews.py", line 509, in
dispatch
response = self.handle_exception(exc) File "D:jwtlibsite-packagesrest_frameworkviews.py", line 469, in
handle_exception
self.raise_uncaught_exception(exc) File "D:jwtlibsite-packagesrest_frameworkviews.py", line 480, in
raise_uncaught_exception
raise exc File "D:jwtlibsite-packagesrest_frameworkviews.py", line 506, in
dispatch
response = handler(request, *args, **kwargs) File "D:djangoauthapi1accountviews.py", line 13, in post
user= serializer.save() File "D:jwtlibsite-packagesrest_frameworkserializers.py", line 212, in
save
self.instance = self.create(validated_data) File "D:jwtlibsite-packagesrest_frameworkserializers.py", line 981, in
create
raise TypeError(msg) TypeError: 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 UserRegistrationSerializers.create() method to handle
this correctly. Original exception was: Traceback (most recent call
last): File
"D:jwtlibsite-packagesrest_frameworkserializers.py", line 962, in
create
instance = ModelClass._default_manager.create(**validated_data) File "D:jwtlibsite-packagesdjangodbmodelsmanager.py", line 85,
in manager_method return getattr(self.get_queryset(), name)(*args,
**kwargs) File "D:jwtlibsite-packagesdjangodbmodelsquery.py", line 669, in create
obj = self.model(**kwargs) File "D:jwtlibsite-packagesdjangodbmodelsbase.py", line 565, in
init
raise TypeError( TypeError: User() got unexpected keyword arguments: ‘password2’

i have figured out each line of code but i am unable to catch what is exactly the error, please needful help is required.

Asked By: Filbadeha

||

Answers:

Because your serializer has password2 but User model does not have.

Just pop password2 into validated_data

from rest_framework import serializers
from account.models import User

class UserRegistrationSerializers(serializers.ModelSerializer):
    password2=serializers.CharField(style={'input_type':'password'}, write_only=True)
    class Meta:
        model = User
        fields=['email','name','tc','password','password2']
        extra_kwargs={
            'password':{'write_only':True}
        }

def validate(self, attrs):
    password=attrs.get('password')
    password2=attrs.pop('password2')
    if password != password2:
        raise serializer.ValidationError("Password and Confirm Password Does not match")
    return attrs

def create(self, validate_data):
    return User.objects.create_user(**validate_data)
Answered By: Utkucan Bıyıklı

How to solve this issue, I have the same issue like this, can anyone explain it please

Answered By: Naeem Chaudry