Django,如何从modelform的choicefield中删除空白选择? [英] Django, how to remove the blank choice from the choicefield in modelform?
问题描述
我创建了一个带有外键的模型:
I created a model with a foreign key in it:
class Book(models.Model):
library = models.ForeignKey(Library, null=False, blank=False)
...
,然后我创建了一个带有ModelForm的表单以显示给用户:
and then I created a form with a ModelForm to display to the users:
class BookSubmitForm(ModelForm):
class Meta:
model = Book
,当我以以下形式显示页面时获得库选项,还获得默认出现的空白(--------)选项。
and when I display the page with the form I get the Library choices but also the blank (--------) choice that comes by default.
我认为通过null = False和blank = False在模型中可以摆脱ModelForm中的空白选择,但没有。我该怎么办才能只在列表中有实际选择,而不是那个?
I thought by having null=False and blank=False in the model that would get rid of that blank choice in the ModelForm but no. What can I do to only have actual choices in the list and not that one?
推荐答案
请参见 ModelChoiceField 。您必须将empty_label设置为None。因此,您的代码将类似于:
See ModelChoiceField. You have to set empty_label to None. So your code will be something like:
class BookSubmitForm(ModelForm):
library = ModelChoiceField(queryset=Library.objects, empty_label=None)
class Meta:
model = Book
编辑:将字段名称更改为小写
changed the field name to lower case
这篇关于Django,如何从modelform的choicefield中删除空白选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!