为什么浏览器会为select元素添加额外的选项?

时间:2011-10-18 14:53:44

标签: python html django

我在Django中使用日期选择小部件作为注册表单。出于某种原因,如果您提交包含验证错误的页面,则选择中的第一个选项元素将重复。每次刷新都会发生这种情况,因此如果您已经提交了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

2 个答案:

答案 0 :(得分:1)

  1. 这不是关于webkit,而是关于渲染的标记,webkit恰好是渲染你给它的标记,而其他的不是(他们认为它是一个重复的选项)
  2. 问题实际上是,每次执行choices.insert(0..方法时,您都会使用render更改MONTHS的值。所以,不要这样做,改变一次。

答案 1 :(得分:0)

问题在于导入的MONTHS_AP是一个可变的字典,因此通过引用传递。 choices.insert()函数中的create_select()因此每次调用时都会向MONTHS_AP字典添加一个none_value。

我通过创建一个包含月份信息的元组来解决问题,并使用它来代替,因为元组是不可变的。

感谢Issac让我走上正轨,Matt以可读的格式提问。我还要感谢我的一年级老师......; - )