Sunil Kumar Sunil Kumar - 19 days ago 8
Python Question

How to resolve TypeError: __init__() got an unexpected keyword argument '_MAX_LENGTH' in Django

This my models.py code.Can anyone let me know whats wrong with this code ?

from django.db import models
from unittest.util import _MAX_LENGTH

class Album(models.Model):
artist = models.CharField(_MAX_LENGTH=250)
album_title = models.CharField(_MAX_LENGTH=500)
genre = models.CharField(_MAX_LENGTH=100)
album_logo = models.CharField(_MAX_LENGTH=1000)

class Song(models.Model):
album = models.ForeignKey(Album, on_delete = models.CASCADE)
file_type = models.CharField(_MAX_LENGTH=10)
song_title = models.CharField(_MAX_LENGTH=250)


While running command python manage.py migrations music,I am getting this error

Traceback (most recent call last):
File "/home/sunil/workspace/DjangoApp1/manage.py", line 11, in <module>
execute_from_command_line(sys.argv)
File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute()
File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 328, in execute
django.setup()
File "/usr/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/lib/python2.7/dist-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/usr/lib/python2.7/dist-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/sunil/workspace/DjangoApp1/music/models.py", line 5, in <module>
class Album(models.Model):
File "/home/sunil/workspace/DjangoApp1/music/models.py", line 6, in Album
artist = models.CharField(_MAX_LENGTH=250)
File "/usr/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 1081, in __init__
super(CharField, self).__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument '_MAX_LENGTH'


Can anyone let me know how to resolve this issue ?

Answer

max_length (maximum length of the field) should be lower case, without leading underscore (_).

class Album(models.Model):
    artist = models.CharField(max_length=250)
    album_title = models.CharField(max_length=500)
    genre = models.CharField(max_length=100)
    album_logo = models.CharField(max_length=1000)

class Song(models.Model):
    album = models.ForeignKey(Album, on_delete=models.CASCADE)
    file_type = models.CharField(max_length=10)
    song_title = models.CharField(max_length=250)

_MAX_LENGTH from the unittest.util is not for django model, but for unittest 's internal usage to limit length of names to be printed.