How to properly use the “choices” field option in Django

前端 未结 7 2112
孤独总比滥情好
孤独总比滥情好 2020-12-12 23:17

I\'m reading the tutorial here: https://docs.djangoproject.com/en/1.5/ref/models/fields/#choices and i\'m trying to create a box where the user can select the month he was b

相关标签:
7条回答
  • 2020-12-13 00:04

    According to the documentation:

    Field.choices

    An iterable (e.g., a list or tuple) consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) ...]) to use as choices for this field. If this is given, the default form widget will be a select box with these choices instead of the standard text field.

    The first element in each tuple is the actual value to be stored, and the second element is the human-readable name.

    So, your code is correct, except that you should either define variables JANUARY, FEBRUARY etc. or use calendar module to define MONTH_CHOICES:

    import calendar
    ...
    
    class MyModel(models.Model):
        ...
    
        MONTH_CHOICES = [(str(i), calendar.month_name[i]) for i in range(1,13)]
    
        month = models.CharField(max_length=9, choices=MONTH_CHOICES, default='1')
    
    0 讨论(0)
提交回复
热议问题