0

I'm trying to use Enums on Python 3.5 in my Django model. Why am I getting this when trying to migrate?

field=models.CharField(choices=[('RE', 'Red'), ('GR', 'Green'), ('BL', 'Blue'), ('OR', 'Orange'), ('YE', 'Yellow'), ('PU', 'Purple')], default=users.models.COLOR('BL'), max_length=2),
AttributeError: module 'users.models' has no attribute 'COLOR'

-

class User(AbstractBaseUser):

  class COLOR(enum.Enum):
    RED = 'RE'
    GREEN = 'GR'
    BLUE = 'BL'
    ORANGE = 'OR'
    YELLOW = 'YE'
    PURPLE = 'PU'

  //...
  color = models.CharField(max_length=2, choices=((x.value, x.name.title()) for x in COLOR), default=COLOR.BLUE)
6
  • 3.4 and 3.5 are different versions. Commented Mar 28, 2017 at 18:39
  • @user2357112 that's a typo, I'm using Python 3.5 Commented Mar 28, 2017 at 18:39
  • docs.djangoproject.com/en/dev/ref/models/fields/… I think this will help you. Commented Mar 28, 2017 at 18:40
  • @Wencakisa I'm trying to use enums instead just declaring the constants. The error is thrown on the default line, not on the choices line. Commented Mar 28, 2017 at 18:42
  • Why are you trying to specify an enum value as the default there, anyway? I don't think Django would even recognize what COLOR.BLUE is, even if you specified it correctly. Commented Mar 28, 2017 at 18:43

1 Answer 1

1

Since you use a CharField on the model, you can not pass an enum instance (default=COLOR.BLUE) as the default value. You should pass a string instead.

The better way to do this is to define a custom field which knows how to clean enum instances. If you rather to keep things simple and stick to the CharField on the model, then just pass the enum value explicitly (default='BL').

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.