%s() got an unexpected keyword argument '%s'

Raise code
if prop in property_names or opts.get_field(prop):
if kwargs[prop] is not _DEFERRED:
_setattr(self, prop, kwargs[prop])
del kwargs[prop]
except (AttributeError, FieldDoesNotExist):
pass
for kwarg in kwargs:
raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))
super().__init__()
post_init.send(sender=cls, instance=self)
@classmethod
def from_db(cls, db, field_names, values):
if len(values) != len(cls._meta.concrete_fields):
values_iter = iter(values)
Links to the raise (1)
https://github.com/django/django/blob/7cca22964c09e8dafc313a400c428242404d527a/django/db/models/base.py#L507Ways to fix
Steps to reproduce:
Step 1: Create a test directory
$ mkdir test-django
Step 2: Navigate to our test directory
$ cd test-django
Step 3: Run the following command
$ pipenv shell
Step 4: Install django dependency
$ pipenv install django
Step 5: Create a new django project namely project
$ pipenv run django-admin startproject project .
Step 6: Create a new django app namely app
$ pipenv run django-admin startapp app
Step 7: Add your app to the projects settings.py file
INSTALLED_APPS = [
......
'app.apps.AppConfig'
]
Step 8: Add the below code to your app's model.py file
from django.db import models
class Test(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
Step 9: Now, run the command
$ pipenv run python manage.py shell
It will open a python shell for you then run the code
from app.models import Test
Test(first_name='Sam', last_name='jones',work='pilot')
The above code generates the following exception:
>>> Test(first_name='Sam', last_name='Jones', work='pilot')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/user/test-django/app/models.py", line 14, in __init__
super().__init__(*args, **kwargs)
File "/home/user/PyEnvs/test-django-BkqCejI/lib/python3.9/site-packages/django/db/models/base.py", line 503, in __init__
raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))
TypeError: Test() got an unexpected keyword argument 'work'
Fixed version of the code
To fix the exception don't provide the unexpected kwargs argument "work" to the Test model class. Run the below code in the python shell itself to fix the exception.
Test(first_name='Sam', last_name='jones')
Explanation:
The Exception is caused as we provide an kwargs argument namely "work" which the model we created wasn't expecting that argument as a result the "Test() got an unexpected keyword argument 'work'" Exception was caused.