Django:如何从模态表单字段生成的选择元素中排除虚假选项“----"? [英] Django: how to exclude the bogus option '----' from select element generated from modal form field?

查看:14
本文介绍了Django:如何从模态表单字段生成的选择元素中排除虚假选项“----"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 属性.但我想知道是否还有其他更直接的方法来完成同样的任务.

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.

推荐答案

尝试:

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

              

测试这是否适合您.

这篇关于Django:如何从模态表单字段生成的选择元素中排除虚假选项“----"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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