如何正确使用“选择”选项。 Django中的field选项 [英] How to properly use the "choices" field option in Django

查看:72
本文介绍了如何正确使用“选择”选项。 Django中的field选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在此处阅读本教程: https://docs.djangoproject.com/ zh / 1.5 / ref / models / fields /#choices
,我正在尝试创建一个框,用户可以在其中选择出生日期。我尝试过的是

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 born in. What I tried was

 MONTH_CHOICES = (
    (JANUARY, "January"),
    (FEBRUARY, "February"),
    (MARCH, "March"),
    ....
    (DECEMBER, "December"),
)

month = CharField(max_length=9,
                  choices=MONTHS_CHOICES,
                  default=JANUARY)

这是正确的吗?我看到我正在阅读的教程中,由于某种原因,它们首先创建了变量,就像这样

Is this correct? I see that in the tutorial I was reading, they for some reason created variables first, like so

FRESHMAN = 'FR'
SOPHOMORE = 'SO'
JUNIOR = 'JR'
SENIOR = 'SR'

为什么创建这些变量?此外,MONTHS_CHOICES处于名为People的模型中,因此我提供的代码将在数据库中创建名为 People的 Months Choices列,并说明用户单击月份后出生的月份。并提交表单?

Why did they create those variables? Also, the MONTHS_CHOICES is in a model called People, so would the code I provided create a "Months Choices) column in the database called called "People" and would it say what month the user was born in after he clicks on of the months and submits the form?

推荐答案

根据文档


Field.choices

Field.choices

一个迭代器(例如列表或元组),其自身由恰好两个项目组成的
迭代器(例如[(A,B ),(A,B)...])用作此字段的
选择。如果给出此选项,则默认表单小部件
将是带有这些选择的选择框,而不是标准文本

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.

因此,您的代码是正确的,除了您应该定义变量 JANUARY FEBRUARY 等或使用 calendar 模块来定义 MONTH_CHOICES

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')

这篇关于如何正确使用“选择”选项。 Django中的field选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆