Search code examples
pythondjangodjango-modelsdjango-rest-frameworkkeyerror

Getting KeyError: 'first name' in django serializers.py


I am stuck for a long time here. I am getting a KeyError for first name, but if I remove it then the code works. I am also using React for my front-end and its just getting messier.

serializers.py

from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth import authenticate

# User Serializer
class UserSerializer(serializers.ModelSerializer):
  class Meta:
    model = User
    fields = ('id', 'first_name', 'last_name', 'username', 'email')

# Register Serializer
class RegisterSerializer(serializers.ModelSerializer):
  class Meta:
    model = User
    fields = ('id', 'first_name', 'last_name', 'username', 'email', 'password')
    extra_kwargs = {'password': {'write_only': True}}

  def create(self, validated_data):
    user = User.objects.create_user(validated_data['first_name'], validated_data['last_name'], validated_data['username'], validated_data['email'], validated_data['password'])
    # user.save()
    return user

# Login Serializer
class LoginSerializer(serializers.Serializer):
  username = serializers.CharField()
  password = serializers.CharField()

  def validate(self, data):
    user = authenticate(**data)
    if user and user.is_active:
      return user
    raise serializers.ValidationError("Incorrect Credentials")

Logs:

Watching for file changes with StatReloader Performing system checks...

System check identified no issues (0 silenced). May 26, 2021 - 08:36:27 Django version 3.1.7, using settings 'leadmanager.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [26/May/2021 08:36:33] "GET / HTTP/1.1" 200 1009 [26/May/2021 08:36:33] "GET /static/frontend/main.js HTTP/1.1" 200 231194 Unauthorized: /api/auth/user [26/May/2021 08:36:33] "GET /api/auth/user HTTP/1.1" 401 58 Not Found: /favicon.ico [26/May/2021 08:36:33] "GET /favicon.ico HTTP/1.1" 404 4127 Internal Server Error: /api/auth/register Traceback (most recent call last):   File "C:\Users\user\Documents\Python\Django Websites\C4Skills\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)   File "C:\Users\user\Documents\Python\Django Websites\C4Skills\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)   File "C:\Users\user\Documents\Python\Django Websites\C4Skills\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)   File "C:\Users\user\Documents\Python\Django Websites\C4Skills\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)   File "C:\Users\user\Documents\Python\Django Websites\C4Skills\lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)   File "C:\Users\user\Documents\Python\Django Websites\C4Skills\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)   File "C:\Users\user\Documents\Python\Django Websites\C4Skills\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception      
    raise exc   File "C:\Users\user\Documents\Python\Django Websites\C4Skills\lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)   File "C:\Users\user\Documents\Python\Django Websites\lead_manager_react_django-master\leadmanager\accounts\api.py", line 12, in post
    serializer.is_valid(raise_exception=True)   File "C:\Users\user\Documents\Python\Django Websites\C4Skills\lib\site-packages\rest_framework\serializers.py", line 220, in is_valid
    self._validated_data = self.run_validation(self.initial_data)   File "C:\Users\user\Documents\Python\Django Websites\C4Skills\lib\site-packages\rest_framework\serializers.py", line 419, in run_validation
    value = self.to_internal_value(data)   File "C:\Users\user\Documents\Python\Django Websites\C4Skills\lib\site-packages\rest_framework\serializers.py", line 472, in to_internal_value       
    for field in fields:   File "C:\Users\user\Documents\Python\Django Websites\C4Skills\lib\site-packages\rest_framework\serializers.py", line 355, in _writable_fields        
    for field in self.fields.values():   File "C:\Users\user\Documents\Python\Django Websites\C4Skills\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)   File "C:\Users\user\Documents\Python\Django Websites\C4Skills\lib\site-packages\rest_framework\serializers.py", line 349, in fields
    for key, value in self.get_fields().items():   File "C:\Users\user\Documents\Python\Django Websites\C4Skills\lib\site-packages\rest_framework\serializers.py", line 1053, in get_fields
    field_class, field_kwargs = self.build_field(   File "C:\Users\user\Documents\Python\Django Websites\C4Skills\lib\site-packages\rest_framework\serializers.py", line 1199, in build_field
    return self.build_unknown_field(field_name, model_class)   File "C:\Users\user\Documents\Python\Django Websites\C4Skills\lib\site-packages\rest_framework\serializers.py", line 1317, in build_unknown_field    
    raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Field name `first_name` is not valid for model `User`.

But if I remove the first name and last name field it works.

Please help, thanks in advance.


Solution

  • Done!!! Don't validate first_name and last_name