使用RadioSelect覆盖Django Select时选择丢失

时间:2015-11-27 10:26:28

标签: django

鉴于下面的django模型,是否可以自动将字段的子集更新为RadioSelect而不是默认的Select

class ExampleModel(models.Model):
    field1_radios = models.CharField(max_length=1, choices=DEFAULT_CHOICES)
    field2_radios = models.CharField(max_length=1, choices=DEFAULT_CHOICES)
    field3_radios = models.CharField(max_length=1, choices=DEFAULT_CHOICES)
    field4_radios = models.CharField(max_length=1, choices=DEFAULT_CHOICES)
    field5 = models.CharField(max_length=50)
    ...

我可以通过以下方式手动实现:

class ExampleForm(forms.ModelForm):
    class Meta:
        model = ExampleModel
        widgets = {
            'field1_radios': forms.RadioSelect(),
            'field2_radios': forms.RadioSelect(),
            'field3_radios': forms.RadioSelect(),
            'field4_radios': forms.RadioSelect()}

当我尝试自动创建小部件时,选项会丢失(并且不会呈现单选按钮):

def custom_callback(f, *args, **kwargs):
    if f.name.endswith('_radios'):
        formfield = f.formfield()
        formfield.widget = forms.RadioSelect()
        return formfield
    else:
        return f.formfield()

class ExampleForm(forms.ModelForm):
    formfield_callback = custom_callback
    class Meta:
        model = ExampleModel

2 个答案:

答案 0 :(得分:2)

啊,看起来我错过了重新指定原始选择的最后一步,这不是自动完成的:

def custom_callback(f, *args, **kwargs):
    if f.name.endswith('_radios'):
        formfield = f.formfield()
        formfield.widget = forms.RadioSelect(choices=formfield.choices)
        return formfield
    else:
        return f.formfield()

答案 1 :(得分:1)

我没有经常使用formfield_callback,我认为它没有记录。

另一种方法是覆盖formfield_for_choice_field

class MyModelAdmin(admin.ModelAdmin):
    ...

    def formfield_for_choice_field(self, db_field, request, **kwargs):
        """Use a radio select instead of a select box"""
        kwargs['widget'] = forms.RadioSelect
        if 'choices' not in kwargs:
            # this was required to prevent displaying the empty label ---------
            kwargs['choices'] = db_field.get_choices(include_blank=False)
        return super(MyModelAdmin, self).formfield_for_choice_field(db_field, request, **kwargs)