我在Django使用一个日期选择小部件作为注册表单。出于某种原因,如果提交的页面出现验证错误,则select中的第一个option元素将重复。每次刷新都会发生这种情况,因此如果您提交了5次页面,那么第一个元素将重复6次。更奇怪的是,小部件由3个选择组成:日、月、年,而这只发生在月选择上。
如有任何意见,将不胜感激。
编辑:
链接到页面:http://gfc.beta-site.co.za:8000/accounts/register/
代码:
import time
import datetime
import re
from django.forms.widgets import Widget, Select
from django.utils import datetime_safe
from django.utils.dates import MONTHS_AP as MONTHS
from django.utils.safestring import mark_safe
from django.utils.formats import get_format
from django.conf import settings
__all__ = ('SelectDateWidget',)
RE_DATE = re.compile(r'(\d{4})-(\d\d?)-(\d\d?)$')
class SelectDateWidget(Widget):
"""
A Widget that splits date input into three <select> boxes.
This also serves as an example of a Widget that has more than one HTML
element and hence implements value_from_datadict.
"""
none_value = (0, '---')
month_field = '%s_month'
day_field = '%s_day'
year_field = '%s_year'
def __init__(self, attrs=None, years=None, required=True):
# years is an optional list/tuple of years to use in the "year" select box.
self.attrs = attrs or {}
self.required = required
if years:
self.years = years
else:
this_year = datetime.date.today().year - 10
self.years = list(range(1942, this_year))
self.years.reverse()
#self.years = range(this_year, this_year+10)
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, basestring):
if settings.USE_L10N:
try:
input_format = get_format('DATE_INPUT_FORMATS')[0]
# Python 2.4 compatibility:
# v = datetime.datetime.strptime(value, input_format)
# would be clearer, but datetime.strptime was added in
# Python 2.5
v = datetime.datetime(*(time.strptime(value, input_format)[0:6]))
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, (0,'Year'), 'dob_year')
choices = MONTHS.items()
month_html = self.create_select(name, self.month_field, value, month_val, choices, (0,'Month'), 'dob_month')
choices = [(i, i) for i in range(1, 32)]
day_html = self.create_select(name, self.day_field, value, day_val, choices, (0,'Day'), 'dob_day')
format = get_format('DATE_FORMAT')
escaped = False
output = []
for char in format:
if escaped:
escaped = False
elif char == '\\':
escaped = True
elif char in 'Yy':
output.append(year_html)
elif char in 'bFMmNn':
output.append(month_html)
elif char in 'dj':
output.append(day_html)
return mark_safe(u'\n'.join(output))
def id_for_label(self, id_):
return '%s_month' % id_
id_for_label = classmethod(id_for_label)
def value_from_datadict(self, data, files, name):
y = data.get(self.year_field % name)
m = data.get(self.month_field % name)
d = data.get(self.day_field % name)
if y == m == d == "0":
return None
if y and m and d:
if settings.USE_L10N:
input_format = get_format('DATE_INPUT_FORMATS')[0]
try:
date_value = datetime.date(int(y), int(m), int(d))
except ValueError:
pass
else:
date_value = datetime_safe.new_date(date_value)
return date_value.strftime(input_format)
else:
return '%s-%s-%s' % (y, m, d)
return data.get(name, None)
def create_select(self, name, field, value, val, choices, none_value, class_name = None):
if 'id' in self.attrs:
id_ = self.attrs['id']
else:
id_ = 'id_%s' % name
if not (self.required and val):
choices.insert(0, none_value)
local_attrs = self.build_attrs(id=field % id_)
s = Select(choices=choices)
select_html = '<div class="'+ class_name +'">' + s.render(field % name, val, local_attrs) + "</div>"
return select_html
最佳答案
这不是关于webkit,而是关于呈现的标记,webkit只是碰巧呈现了您给它的标记,而其他人没有(他们将其视为一个重复的选项)
问题是实际上,在每次执行choices.insert(0..
方法时,您都在用render
更改月份值。所以,别这样,换一次。
关于python - 为什么浏览器向我的选择元素添加额外的选项?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7809286/