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

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

问题描述

我在这里阅读教程:https://docs.djangoproject.com/en/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.

所以,你的代码是正确的,除了你应该定义变量JANUARYFEBRUARY等,或者使用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 中的字段选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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