【问题标题】:build_attrs() got an unexpected keyword argument 'id'build_attrs() 得到了一个意外的关键字参数“id”
【发布时间】:2018-08-02 09:06:37
【问题描述】:

我正在尝试使用月份和年份下拉菜单获取日期输入。 我正在使用来自 django sn-p 的小部件。

关于小部件: 一个将日期输入分成月份和年份两个框的小部件, 'day' 默认为每月的第一天。

这是小部件的代码

import datetime
import re
from six import string_types
from django.forms.widgets import Widget, Select
from django.utils.dates import MONTHS
from django.utils.safestring import mark_safe

__all__ = ('MonthYearWidget',)

RE_DATE = re.compile(r'(\d{4})-(\d\d?)-(\d\d?)$')


class MonthYearWidget(Widget):
    """
    A Widget that splits date input into two <select> boxes for month and year,
    with 'day' defaulting to the first of the month.

    Based on SelectDateWidget, in

    django/trunk/django/forms/extras/widgets.py


    """
    none_value = (0, '---')
    month_field = '%s_month'
    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
            self.years = range(this_year, this_year+10)

    def render(self, name, value, attrs=None):
        try:
            year_val, month_val = value.year, value.month
        except AttributeError:
            year_val = month_val = None
            if isinstance(value, string_types):
                match = RE_DATE.match(value)
                if match:
                    year_val, month_val, day_val = [int(v) for v in match.groups()]

        output = []

        if 'id' in self.attrs:
            id_ = self.attrs['id']
        else:
            id_ = 'id_%s' % name

        month_choices = list(MONTHS.items())
        if not (self.required and value):
            month_choices.append(self.none_value)
        month_choices.sort()
        local_attrs = self.build_attrs(id=self.month_field % id_)
        s = Select(choices=month_choices)
        select_html = s.render(self.month_field % name, month_val, local_attrs)
        output.append(select_html)

        year_choices = [(i, i) for i in self.years]
        if not (self.required and value):
            year_choices.insert(0, self.none_value)
        local_attrs['id'] = self.year_field % id_
        s = Select(choices=year_choices)
        select_html = s.render(self.year_field % name, year_val, local_attrs)
        output.append(select_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)
        if y == m == "0":
            return None
        if y and m:
            return '%s-%s-%s' % (y, m, 1)
        return data.get(name, None)

我的浏览器出现这个错误

TypeError: build_attrs() got an unexpected keyword argument 'id'

我的python版本是3.7.0,django版本是2.0.7

如何摆脱这个错误?

【问题讨论】:

  • build_attrs 方法在哪里???它需要一个 ID 值吗?
  • 你可能想要build_attrs(extra_attrs={'id': self.month_field % id_})
  • @OhadtheLad 即使我也有同样的疑问并搜索了该方法,但找不到它
  • @WillemVanOnsem 那么我应该在代码中的任何地方用 extra_attrs 替换 build_attrs 吗?
  • @WillemVanOnsem 你说得对,很好!

标签: python django django-forms


【解决方案1】:

您应该将 id 值作为字典值传递:

local_attrs = self.build_attrs(attrs, {'id':'self.month_field % id_'})

在 Django 1.11 中,Widget.build_attrs() 签名已更改,因此它只有两个参数:

Django 1.11 fix #28095

查看用户 Ruan Steenkamp 在 stackoverflow 问题中解决的类似问题: Update to 1.11: TypeError build_attrs() takes at most 2 arguments (3 given)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 2016-09-17
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    相关资源
    最近更新 更多