Home > front end >  Where in Django Charfield() is max_length defined as compulsory?
Where in Django Charfield() is max_length defined as compulsory?

Time:10-08

I have a Django app and trying to understand the logic on how to read docs correctly in order to e.g. create a Charfield object.

So here is my model:

from django.db import models

class Person(models.Model):
    f_name = models.CharField()
    . . . . . . 

If I run the app I get the error:

Charfields must define a 'max_length' attribute

I get that I need to do:

f_name = models.CharField(max_length=40)

But why? when I read the code for Charfield it's not there, so I read the code for its superclass Field but I don't see where max_length is set to be compulsory!

Please assist (new to oop)

CodePudding user response:

Technically, the check is right here in the definition of CharField, as a Django system check (def _check_max_length_attribute(self, **kwargs):):

def _check_max_length_attribute(self, **kwargs):
    if self.max_length is None:
        return [
            checks.Error("CharFields must define a 'max_length' attribute.",
                obj=self,
                id="fields.E120",
            )
        ]
    # ...

It's hooked up to be a Django system check for CharFields in the check function just above.

For future reference, I found it by just searching for CharFields must define a in the Django code base.

  • Related