Sourabh
Sourabh

Reputation: 8482

Django - Use Radio Buttons or Drop Down List for input

I made a model something like this:

class Enduser(models.Model):
    user_type = models.CharField(max_length = 10)

Now I want user_type to have only one of the given values, say any one from ['master', 'experienced', 'noob']

Can I do this with Django?

Also, how can I display a list of radio buttons or drop-down list/select menu to chose one of these values?

Upvotes: 2

Views: 459

Answers (2)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53981

Use model field choices:

CHOICES = (
    ('foo', 'Do bar?'),
    ...
)
class Enduser(models.Model):
    user_type = models.CharField(max_length = 10, choices=CHOICES)

Upvotes: 2

Paulo Bu
Paulo Bu

Reputation: 29794

You can take advantage of the choices attribute for CharField:

class Enduser(models.Model):
    CHOICES = (
       (u'1',u'master'),
       (u'2',u'experienced'),
       (u'3',u'noob'),
       )
    user_type = models.CharField(max_length = 2, choices=CHOICES)

This will save values 1,2 or 3 in the db and when retrieved the object, it will map it to master, experienced or noob. Take a look at the docs for more info.

Hope this helps!

Upvotes: 2

Related Questions