Django:如何从模态窗体字段生成的select元素中排除虚假选项'----'? [英] Django: how to exclude the bogus option '----' from select element generated from modal form field?
本文介绍了Django:如何从模态窗体字段生成的select元素中排除虚假选项'----'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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 属性。但是我想知道是否还有其他更直接的方法来实现这一点。
解决方案
尝试:
$从django.forms导入的$ F $ F $ F $ F $ F
time_unit = forms.forms.TypedChoiceField(
required = True,
choices = Foo.TIME_UNIT_TYPE
)
class Meta:
model = Foo
fields =(time_unit)
测试这是否适合你。
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,)
When time_unit is rendered in the template, the resultant select element contains a bogus '----' option that I don't need for my app. I can remove this bogus option inside init() or redefine the time_unit attribute inside the FooForm. But I was wondering if there are any other more straightforward ways to accomplish the same.
解决方案
Try with:
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,)
Test if this works for you.
这篇关于Django:如何从模态窗体字段生成的select元素中排除虚假选项'----'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文