from django.db import models
class Project(models.Model): """ 項目表 """ COLOR_CHOICES = ( (1, "#56b8eb"), # 56b8eb (2, "#f28033"), # f28033 (3, "#ebc656"), # ebc656 (4, "#a2d148"), # a2d148 (5, "#20BFA4"), # #20BFA4 (6, "#7461c2"), # 7461c2, (7, "#20bfa3"), # 20bfa3, ) color = models.SmallIntegerField(verbose_name='顏色', choices=COLOR_CHOICES, default=1)
有一個表 如上,我們在django中通過 modelForm可以生成一個 下拉框的字段 (默認的)
url 我們略過了 自己定義就好
class ProjectModelForm(BootStrapForm, forms.ModelForm):
class Meta: model = models.Project fields = ['color']
def project_list(request):
form = ProjectModelForm(request)
return render(request, 'project_list.html', {'form': form})
展示圖
改成radio的樣式
class BootStrap(object): bootstrop_class_exclude = [] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name, field in self.fields.items(): if name in self.bootstrop_class_exclude: continue field.widget.attrs['class'] = 'form-control' field.widget.attrs['placeholder'] = '請輸入%s' % (field.label,)
class ProjectModelForm(BootStrap, forms.ModelForm): bootstrop_class_exclude = ['color'] class Meta: model = models.Project fields = ['color'] widgets = {'color':forms.RadioSelect }
但是我們要是效果 如下
怎么做呢? 我們的處理辦法是 自己定制插件
定制插件
第一步:
from django.forms import RadioSelect class ColorRadioSelect(RadioSelect): template_name = 'widgets/color_radio/radio.html' option_template_name = 'widgets/color_radio/radio_option.html' # 只不過是路勁下的一個文件 下面是文件的內容
第二步 文件內容

{% with id=widget.attrs.id %} <div{% if id %} id="{{ id }}"{% endif %}{% if widget.attrs.class %} class="{{ widget.attrs.class }}"{% endif %}> {% for group, options, index in widget.optgroups %} {% for option in options %} <label {% if option.attrs.id %} for="{{ option.attrs.id }}"{% endif %} > {% include option.template_name with widget=option %} </label> {% endfor %} {% endfor %} </div> {% endwith %}

{% include "django/forms/widgets/input.html" %} <span class="cycle" style="background-color:{{ option.label }}"></span>
第三步 使用
class ProjectModelForm(BootStrap, forms.ModelForm): bootstrop_class_exclude = ['color'] class Meta: model = models.Project fields = ['color'] widgets = {'color':ColorRadioSelect(attrs={'class': 'color-radio'}) # 自己寫的 }
可以自己定樣式

.color-radio label { margin-left: 0; padding-left: 0; } /*隱藏input框*/ .color-radio input[type="radio"] { display: none; } .color-radio input[type="radio"] + .cycle { display: inline-block; height: 25px; width: 25px; border-radius: 50%; border: 2px solid #dddddd; } .color-radio input[type="radio"]:checked + .cycle { border: 2px solid black; }