你是否在django后台站点管理中,为select下拉框的默认值‘-------’而烦恼,比如下图中的面试部门。
那么,该如何去掉这个默认值呢?两种办法:
1、模型中设置外键的默认值。
这样做的效果就是表单中的默认值为所有可选项的第一项。
class Interview(models.Model):
department = models.ForeignKey('departments.Department', default='', related_name='interview',
on_delete=models.PROTECT, verbose_name='面试部门')
2、重写xadmin插件的optgroups方法:
这样做的效果同样是表单中的默认值为所有可选项的第一项。
重写位置在\xadmin\widgets.py文件中的AdminSelectWidget类下。
class AdminSelectWidget(forms.Select):
def optgroups(self, name, value, attrs=None):
"""Return a list of optgroups for this widget."""
groups = []
has_selected = False
for index, (option_value, option_label) in enumerate(chain(self.choices)):
if index==0 and option_value=='' and option_label=='---------':# 新加
continue
if option_value is None:
option_value = ''
subgroup = []
if isinstance(option_label, (list, tuple)):
group_name = option_value
subindex = 0
choices = option_label
else:
group_name = None
subindex = None
choices = [(option_value, option_label)]
groups.append((group_name, subgroup, index))
for subvalue, sublabel in choices:
selected = (
force_text(subvalue) in value and
(has_selected is False or self.allow_multiple_selected)
)
if selected is True and has_selected is False:
has_selected = True
subgroup.append(self.create_option(
name, subvalue, sublabel, selected, index,
subindex=subindex, attrs=attrs,
))
if subindex is not None:
subindex += 1
return groups