列出django中的ChoiceField作为Button [英] Listing a ChoiceField in django as Button

查看:41
本文介绍了列出django中的ChoiceField作为Button的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是否可以将django中ChoiceField的表示方式从下拉列表更改为类似按钮的按钮,每个按钮都有不同的选择?

解决方案

如果只需要更改样式,则可以将css类作为属性传递.请参见

如果需要更好的自定义,则可以覆盖默认的窗口小部件模板,并放置所需的任何html.请参见

Is there a way for me to change the way ChoiceFields are represented in django from a drop down list to something like buttons with each having a different choice ?

If you just need to change the style, you can pass the css class as attribute. See the Docs

select_media = forms.ChoiceField(widget=forms.Select(
    attrs={'class': 'btn btn-primary'}),
    choices=MEDIA_CHOICES)

If you need finer customization, you can override the default widget templates and put whatever html you want.See the docs here. Below code is for Django 1.11

class CustomSelectWidget(forms.Select):
    template_name: 'yourapp/select.html'
    option_template_name =  'yourapp/select_option.html'

class CustomForm(forms.Form):
    MEDIA_CHOICES = (
        (1, 'DVD'),
        (2, 'VCD'),
        (3,'USB')
        )
    select_media = forms.ChoiceField(widget=CustomSelectWidget(
        attrs={'class': 'btn btn-primary'}),
        choices=MEDIA_CHOICES)

这篇关于列出django中的ChoiceField作为Button的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆