【问题标题】:Django: how to exclude the bogus option '----' from select element generated from modal form field?Django:如何从模态表单字段生成的选择元素中排除虚假选项'----'?
【发布时间】:2012-01-03 11:01:08
【问题描述】:

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 在模板中呈现时,生成的 select 元素 包含我的应用不需要的虚假“----”选项。我可以删除 init() 中的这个虚假选项或重新定义 FooForm 中的 time_unit 属性。但我想知道是否还有其他更直接的方法可以完成同样的任务。

【问题讨论】:

    标签: django django-models django-forms


    【解决方案1】:

    尝试:

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

    测试这是否适合你。

    【讨论】:

    • 我试过 empty_label 但这不起作用,因为 empty_label 仅适用于 forms.ModelChoiceField 但 time_unit 是 forms.TypedChoiceField。
    • 我不知道。好电话 - here is the docs for it
    • @pastylegs - 见我上面的评论。
    • 如果你查看the code for the empty_label,你可以很容易地在你自己的init中复制它
    • 后者;自定义表单字段,而不是具有自定义 init 的表单。除非两者之间存在问题,但我认为您应该使用最简单的方法
    【解决方案2】:

    没有特别容易/更少的代码。您也可以为您的 time_unit 创建自己的字段,扩展默认 ChoiceField 的 the _get_choices() method 并在您的 time_unit 模型字段上使用它,如果您认为这样更干净但工作量更大

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-06
      • 2012-02-06
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多