Django: how to exclude the bogus option '----' from select element generated from modal form field?

て烟熏妆下的殇ゞ 提交于 2019-12-18 09:27:50

问题


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.


回答1:


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.




回答2:


None that are particularly easier/less code. You could alternatively create your own Field for your time_unit, extend the _get_choices() method of the default ChoiceField and use it on your time_unit model field if you thought that was cleaner but that's much more work



来源:https://stackoverflow.com/questions/8220404/django-how-to-exclude-the-bogus-option-from-select-element-generated-fro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!