DEV Community

MarkPy
MarkPy

Posted on • Edited on

6 1

working with Django model ChoiceField

Today we going to explore how to work with model ChoiceField in Django.
To better understand, let's see the following examples.

#models.py
#Django Models ChoiceField    
class Profile(models.Model):
    # Country 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 

Enter fullscreen mode Exit fullscreen mode

Result:

Alt text of image

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

Enter fullscreen mode Exit fullscreen mode

Result:

Alt text of image

Reference:
Django Model ChoiceField

All Done!

Sentry image

How we debugged a broken checkout flow in Flask + React

Dropped carts = lost revenue. See how Sentry tracing can catch a full-stack bug in a Flask + React checkout flow—before it can become a support fire drill.

Read more →

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay