2013-07-10 72 views
2

我做了一個模型是這樣的:Django的 - 使用單選按鈕或下拉列表中輸入

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

現在我想user_type只具有給定值中的一個,說從['master', 'experienced', 'noob']

任何一個

我可以用Django做這個嗎?

另外,如何顯示單選按鈕列表或下拉列表/選擇菜單以選擇其中一個值?

回答

2

您可以利用choices屬性爲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) 

這將節省值在DB 1,2 or 3,當檢索到的對象後,將其映射到master, experienced or noob。請參閱the docs瞭解更多信息。

希望這會有所幫助!

2

Use model field choices:

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