本文介绍了在SelectDateWidget中为每个选择添加div包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以覆盖SelectDateWidget以围绕每个选择包围一个div?
Is it possible to overwrite SelectDateWidget to wrap a div around each select?
像这样:
<div class="wrapper">
<select class="selectdatewidget form-control" id="id_birthdate_day" name="birthdate_day">
<option value="0">---</option>....
</select>
</div>
<div class="wrapper">
<select class="selectdatewidget form-control" id="id_birthdate_month" name="birthdate_month">
<option value="0">---</option>....
</select>
</div>
<div class="wrapper">
<select class="selectdatewidget form-control" id="id_birthdate_year" name="birthdate_year">
<option value="0">---</option>....
</select>
</div>
推荐答案
您可以继承SelectDateWidget并覆盖它。之后,您可以使用您的CustomSelectDateWidget窗体。
You can inherit the SelectDateWidget and override the render method within it. After that, you can use your CustomSelectDateWidget in the form.
例如:
class CustomSelectDateWidget (SelectDateWidget):
"""Override of the standard renderer used for SelectDateWidget"""
def render(self, name, value, attrs=None):
try:
year_val, month_val, day_val = value.year, value.month, value.day
except AttributeError:
year_val = month_val = day_val = None
if isinstance(value, six.string_types):
if settings.USE_L10N:
try:
input_format = get_format('DATE_INPUT_FORMATS')[0]
v = datetime.datetime.strptime(value, input_format)
year_val, month_val, day_val = v.year, v.month, v.day
except ValueError:
pass
else:
match = RE_DATE.match(value)
if match:
year_val, month_val, day_val = [int(v) for v in match.groups()]
choices = [(i, i) for i in self.years]
year_html = self.create_select(name, self.year_field, value, year_val, choices)
choices = list(six.iteritems(MONTHS))
month_html = self.create_select(name, self.month_field, value, month_val, choices)
choices = [(i, i) for i in range(1, 32)]
day_html = self.create_select(name, self.day_field, value, day_val, choices)
output = []
for field in _parse_date_fmt():
if field == 'year':
output.append('<div class="wrapper">' + year_html + '</div>')
elif field == 'month':
output.append('<div class="wrapper">' + month_html + '</div>')
elif field == 'day':
output.append('<div class="wrapper">' + day_html + '</div>')
return mark_safe('\n'.join(output))`
重要的一点是代码的结尾。这应该工作,没有测试。我建议从Django中的自己的SelectDateWidge版本中复制渲染方法(我正在运行Django 1.5),并用附加的div覆盖该部分。
The important bit is towards the end of the code. This should work, not tested though. I would suggest copy the render method from your own version of SelectDateWidge within Django (I am running Django 1.5) and override the part with the div appended.
这篇关于在SelectDateWidget中为每个选择添加div包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!