Last modified: April 20, 2020

Using Django Model ChoiceField [Simple Examle]

Today we going to explore how to work with model ChoiceField in Django.

To better understand, let's see the following examples.

Django Models ChoiceField example

models.py


#models.py

#Django Models ChoiceField    
class Profile(models.Model):
    # Countries Choices
    CHOICES = (
        ('US', 'United States'),
        ('FR', 'France'),
        ('CN', 'China'),
        ('RU', 'Russia'),
        ('IT', 'Italy'),
    )
    username = models.CharField(max_length=300)
    country = models.CharField(max_length=300, choices = CHOICES)

    def __str__(self):
        return self.username    


admin page

Django Models ChoiceField

Grouped Model ChoiceField


class Profile(models.Model):
    # Country Choices
    CHOICES = [
    ('Europe', (
            ('FR', 'France'),
            ('ES', 'Spain'),
        )
    ),
    ('Africa', (
            ('MA', 'Morocco'),
            ('DZ', 'Algeria'),
        )
    ),
    ]
    username = models.CharField(max_length=300)
    country = models.CharField(max_length=300, choices = CHOICES)

    def __str__(self):
        return self.username   


admin page

Django Models ChoiceField