models.py:
class Foo(models.Model):
...
TIME_UNIT_TYPE = (
('D', 'Day'),
('W', 'Week'),
('M', 'Month'),
)
time_unit = models.CharField(max_length=1, choices=TIME_UNIT_TYPE)
...
forms.py:
class FooForm(ModelForm):
class Meta:
model = Foo
fields = (time_unit,)
在模板中呈现 time_unit 时,生成的选择元素包含我的应用程序不需要的伪造“----”选项。我可以在 init ()中删除此伪造选项,或重新定义FooForm中的 time_unit 属性。但我想知道是否还有其他更直接的方法来实现同样的目标。
答案 0 :(得分:2)
尝试:
from django.forms import ModelForm
from django import forms as forms
class FooForm(ModelForm):
time_unit = forms.forms.TypedChoiceField(
required=True,
choices = Foo.TIME_UNIT_TYPE
)
class Meta:
model = Foo
fields = (time_unit,)
测试这是否适合你。
答案 1 :(得分:1)
没有特别容易/更少的代码。您也可以为time_unit创建自己的Field,扩展默认ChoiceField的the _get_choices()
method并在 time_unit 模型字段中使用它,如果您认为它更干净但是更多的工作