django admin - 自定义字段radio - admin.HORIZONTAL无效

时间:2014-10-16 12:29:11

标签: django django-forms django-admin

我在django admin中将此自定义字段image_choice作为无线电选择。

IMG_CHOICES = (
   ('embed', _('Embed code')),
   ('file', _('Upload image')),
   ('link', _('Image Link'))
)

class BlogArticleForm(forms.ModelForm):
   class Media:
       js = ('js/myjs.js')
   image_choice = forms.ChoiceField(choices=IMG_CHOICES, widget=forms.RadioSelect)


class BlogArticleAdmin(admin.ModelAdmin):
   form = BlogArticleForm
   fields = ['title', 'description', 'image_choice', 'image_embed', 'image_file', 'image_link']


admin.site.register(models.BlogArticle, BlogArticleAdmin)

我不能让这些单选按钮水平排列。

我试过了:

radio_fields = {'image_choice': admin.HORIZONTAL}

radio_fields = {form.image_choice: admin.HORIZONTAL}

但我一直收到这个错误:

type object "BlogArticleForm" has no attribute 'image_choice'

我怎样才能做到这一点?

这就是它现在的样子:

enter image description here

1 个答案:

答案 0 :(得分:1)

看一下这个line 所以我想它看起来应该是这样的:

from django.contrib.admin.options import get_ul_class

class BlogArticleForm(forms.ModelForm):
   image_choice = forms.ChoiceField(
                            choices=IMG_CHOICES,
                            widget=widgets.AdminRadioSelect(
                               attrs={'class': get_ul_class(admin.HORIZONTAL)}
                            ))

UPD :我是傻瓜:(
它说:if 'widget' not in kwargs: bla-bla-bla添加了widget。所以这应该适用于没有小部件:

image_choice = forms.ChoiceField(choices=IMG_CHOICES)

# And set 
radio_fields = {'image_choice': admin.HORIZONTAL}