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; 25px; border-radius: 50%; border: 2px solid #dddddd; } .color-radio input[type="radio"]:checked + .cycle { border: 2px solid black; }