ModelChoiceField:删除空选项并选择默认值

时间:2020-07-30 11:27:10

标签: django django-1.8

我正在使用@RunWith(SpringRunner.class) @SpringBatchTest @SpringBootTest(classes = ArchiverBatchConfiguration.class) public class ArchiveStepAcceptanceTest { @Autowired private JobLauncherTestUtils jobLauncherTestUtils; @Autowired private JobRepositoryTestUtils jobRepositoryTestUtils; // And the actual tests follow... } 字段的默认表单字段,该字段是使用BatchConfigurer小部件的models.ForeignKey

有问题的相关模型是ModelChoiceField,并且该字段被设置为可空值,因此它不会对数百个现有条目强制使用默认值。但是,实际上,我们的默认值应该是星期天,即Select

默认情况下,呈现时的null字段的选择小部件显示null选项。我该如何放弃此选项而改为使用默认值?

如果我设置一个初始值,则默认情况下会在新表单上选择该初始值:

Weekday

但是仍然列出空值。我尝试覆盖小部件选择:

Weekday.objects.get(day_of_week=6)

但是,现在默认情况下未选择“星期日”。我以为也许我需要使用选项值作为初始值,但这也不起作用:

self.fields['start_weekday'].initial = Weekday.objects.get(day_of_week=6)

简而言之:如何在可为空的模型字段中删除空选项并改为选择默认值?

1 个答案:

答案 0 :(得分:0)

empty_label=None中提供ModelChoiceField

start_weekday = ModelChoiceField(Weekday.objects.filter(day_of_week=6), empty_label=None)

OR

代替分配首字母,也可以分配empty_label

self.fields['start_weekday'].empty_label = None

OR

您还可以在模型的字段中提供默认值

start_weekday = models.CharField(max_length=10,choices=[(wd.day_of_week, wd.name) for wd in Weekday.objects.all()],default=6)