Sometimes ChoiceField can be useful in our models, one typical example for it is when you have for example different User profile types.
If you need to add this kind of limited choices for an UserType ('admin', 'blog_manager', 'translator', 'normal'...) we could use ChoiceField, let's check the code example:
PROFILE_ROLE_CHOICES = (
('admin', _('Administrator')),
('b_manager', _('Blog Manager')),
('trans', _('Translator')),
('normal', _('Normal user')),
)
class Profile(model.Model)
user = models.OneToOneField(User)
user_type = models.CharField(max_length=10, choices=USERTYPE_CHOICES, default='normal', verbose_name=_('user type'))
# other fields...
The important lines there are the definition of the choices (above the class) and the definiton of the user_type field.
Now let's check some examples to learn how to manage this field:
# Creating User Profile with user_type by default
user = User.objects.all()[0]
new_profile = Profile(user=user)
new_profile.save()
print new_profile.user_type
Output: 'normal'
user_type has been defined with a default value, If we don't set the user_type it will be set to 'normal' by default
To configure manually other user_type, we just need to pass the string like:
# Creating User Profile setting the user_type manually
user = User.objects.all()[0]
new_profile = Profile(user=user, user_type='b_manager')
new_profile.save()
print new_profile.user_type
Output: 'b_manager'
If you have any doubt please add a comment !