Sunil Kumar Sunil Kumar - 1 year ago 200
Python Question

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

This my 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 migrations music,I am getting this error

Traceback (most recent call last):
File "/home/sunil/workspace/DjangoApp1/", line 11, in <module>
File "/usr/lib/python2.7/dist-packages/django/core/management/", line 354, in execute_from_command_line
File "/usr/lib/python2.7/dist-packages/django/core/management/", line 328, in execute
File "/usr/lib/python2.7/dist-packages/django/", line 18, in setup
File "/usr/lib/python2.7/dist-packages/django/apps/", line 108, in populate
File "/usr/lib/python2.7/dist-packages/django/apps/", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python2.7/importlib/", line 37, in import_module
File "/home/sunil/workspace/DjangoApp1/music/", line 5, in <module>
class Album(models.Model):
File "/home/sunil/workspace/DjangoApp1/music/", line 6, in Album
artist = models.CharField(_MAX_LENGTH=250)
File "/usr/lib/python2.7/dist-packages/django/db/models/fields/", 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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download