Home > Blockchain >  Getting Typerror in django but fields appear to be defined correctly
Getting Typerror in django but fields appear to be defined correctly

Time:10-21

I'm brand new to django and I can't figure out why this is happening. Here is my model which I have added to my settings "Installed Apps" config and I have migrated:

class User(models.Model):
    name = models.CharField(max_length = 200),
    state = models.CharField

In the shell I import the model like so:

from homepage.models import User

then I try to create a new user like so:

a = User(name='Alex', state='Alberta')

and it throws this error which makes no sense to me because I've defined the fields of the User schema above: I know I'm missing something like maybe I'm supposed to add something to my views.py file before starting the shell but I just don't know. Any direction appreciated! Thanks!

TypeError                                 Traceback (most recent call last)
<ipython-input-3-88cc332f436e> in <module>
----> 1 a = User(name='Alex Honing', state='Alberta')

/usr/local/anaconda3/envs/pyfinance/lib/python3.9/site-packages/django/db/models/base.py in __init__(self, *args, **kwargs)
    501                     pass
    502             for kwarg in kwargs:
--> 503                 raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))
    504         super().__init__()
    505         post_init.send(sender=cls, instance=self)

TypeError: User() got an unexpected keyword argument 'name'

In [4]: a = User(name = 'Alex', state ='Alberta')

CodePudding user response:

Your model has an extra , and the state field is not instantiated. All fields declared on models must be instantiated.

A valid implementation will look something like this:

class User(models.Model):
    name = models.CharField(max_length=200)
    state = models.CharField(max_length=200)
  • Related