django: how to pass css to form.as_ul
my form is
class Form(forms.Form):
ability = forms.ChoiceField(widget= forms.CheckboxSelectMultiple(), choices = SKILLS, required=False)
i am displaying it as {{ Form.开发者_C百科as_ul }}
how do i pass a css ul class to this? Can i do it somewhere in the template? not sure how this works
Unfortunately you have to create a new widget, but you can use the __init__
and render
functions of the existing CheckboxSelectMultiple
widget.
Add a new ul_attrs
parameter to the contructor.
from django import forms
from django.forms.util import flatatt
from django.utils.safestring import mark_safe
class MyCheckboxSelectMultiple(forms.CheckboxSelectMultiple):
def __init__(self, attrs=None, ul_attrs=None):
self.ul_attrs = ul_attrs
super(MyCheckboxSelectMultiple, self).__init__(attrs)
def render(self, name, value, attrs=None, choices=()):
html = super(MyCheckboxSelectMultiple, self).render(name, value, attrs, choices)
final_attrs = self.build_attrs(self.ul_attrs)
return mark_safe(html.replace('<ul>','<ul%s>' % flatatt(final_attrs)))
In your form simply use this custom widget:
class Form(forms.Form):
ability = forms.ChoiceField(widget= MyCheckboxSelectMultiple(ul_attrs={"class":"fancybox"}), choices = SKILLS, required=False)
#
You can pass HTML attributes to the widget via the attrs
parameter. Also, take a look at chapter 7 of the Django book, especially the section Customizing Form Design.
Section teaser:
While it’s convenient to have our form’s HTML generated for us, in many cases you’ll want to override the default rendering.
{{ form.as_table }}
and friends are useful shortcuts while you develop your application, but everything about the way a form is displayed can be overridden, mostly within the template itself, and you’ll probably find yourself doing this.
since Django 1.11, you can Overriding built-in widget templates:
class MyCheckboxSelectMultiple(forms.CheckboxSelectMultiple):
template_name = 'widgets/multiple_input.html'
and copy
django/forms/widgets/multiple_input.html
, which included by django/forms/widgets/checkbox_select.html
to
your_app/templates/widgets
directory.
Now, customize class or style in your_app/templates/widgets/multiple_input.html
file.
精彩评论