分析widget:
class TestForm(forms.Form): user = fields.CharField( required = True, widget = widgets.TextInput() )
追踪widgets.py
__all__ = ( ‘Media‘, ‘MediaDefiningClass‘, ‘Widget‘, ‘TextInput‘, ‘NumberInput‘, ‘EmailInput‘, ‘URLInput‘, ‘PasswordInput‘, ‘HiddenInput‘, ‘MultipleHiddenInput‘, ‘FileInput‘, ‘ClearableFileInput‘, ‘Textarea‘, ‘DateInput‘, ‘DateTimeInput‘, ‘TimeInput‘, ‘CheckboxInput‘, ‘Select‘, ‘NullBooleanSelect‘, ‘SelectMultiple‘, ‘RadioSelect‘, ‘CheckboxSelectMultiple‘, ‘MultiWidget‘, ‘SplitDateTimeWidget‘, ‘SplitHiddenDateTimeWidget‘, ‘SelectDateWidget‘, )
class TextInput(Input): input_type = ‘text‘ template_name = ‘django/forms/widgets/text.html‘ #模板html存放路径
追踪父类:
class Input(Widget): """ Base class for all <input> widgets. """ input_type = None # Subclasses must define this. template_name = ‘django/forms/widgets/input.html‘ def __init__(self, attrs=None): #发现这里又参数attrs可以设置属性 if attrs is not None: attrs = attrs.copy() self.input_type = attrs.pop(‘type‘, self.input_type) super(Input, self).__init__(attrs) def get_context(self, name, value, attrs): context = super(Input, self).get_context(name, value, attrs) context[‘widget‘][‘type‘] = self.input_type return context
发现模板文件template_name = ‘django/forms/widgets/input.html‘,实际上并不存在,是调用了父类方法
class Widget(six.with_metaclass(RenameWidgetMethods)): def get_context(self, name, value, attrs): context = {} context[‘widget‘] = { ‘name‘: name, ‘is_hidden‘: self.is_hidden, ‘required‘: self.is_required, ‘value‘: self.format_value(value), ‘attrs‘: self.build_attrs(self.attrs, attrs), ‘template_name‘: self.template_name, } return context def render(self, name, value, attrs=None, renderer=None): """ Returns this Widget rendered as HTML, as a Unicode string. #生成对于html代码,返回使用 """ context = self.get_context(name, value, attrs) return self._render(self.template_name, context, renderer) def _render(self, template_name, context, renderer=None): if renderer is None: renderer = get_default_renderer() return mark_safe(renderer.render(template_name, context))
所以我们可以自定制样式,属性
widget = widgets.TextInput(attrs={"class":"c1"}),#这个属性,在前端进行设置就可以生成想要的样式
补充:在服务端生成原生字符串,不需要前端渲染时进行转义
txt = "<input type=‘text‘ />" #默认发送到模板页面是无法显示需要进行处理 #在views中处理: fromdjango.utils.safestring import make_safe txt = mark_safe(txt) #前端可以正常显示
select单选框:
sel_inp=fields.ChoiceField( choices = [(1,‘a‘),(2,‘b‘),] )
select框:
sel_inp = fields.CharField( widget = widgets.Select(choices=[(1,‘a‘),(2,‘b‘),]) )
combo多选:
radio_inp=fields.MultipleChoiceField( choices = [(1,‘a‘),(2,‘b‘),] #含有multiple时可以写在外,也可以写在内,这里推荐在外 widget = widgets.SelectMultiple(attrs={‘class‘:"c1"}) )
单选CheckBox:
chk_inp = fields.CharField( widget = widgets.CheckboxInput() )
多选CheckBox
mchk_inp = fields.MultipleChoiceField( widget = widgets.CheckboxSelectMultiple(), choices=[(1, "d"), (2, "e"),(3,‘r‘) ], initial = [2,3] )
radio单选:
rad_inp = fields.ChoiceField( choices=[(1,"男"),(2,"女"),], initial=2, widget =widgets.RadioSelect(), )
字段用于保存正则表达式,Html插件用于生产HTML标签(input)