django - TypeError build_attrs() 在 django 中得到了一个意外的关键字参数 'id'
问题描述
一般来说,什么会导致 build_attrs() 出现意外的关键字参数“id”错误?
特别是在我的项目从一台服务器迁移到另一台服务器后,我遇到了这个错误。所有模板都呈现得很好。我不知道在哪里搜索以修复它。会不会是模板引发的错误?
我的观点
@method_decorator(user_access_to_log, name='dispatch')
class StatisticsView(LoginRequiredMixin,ListView, FormMixin):
model = RequestRequest
login_url = '/login/'
template_name = 'statistics.html'
form_class = DateMonthForm
def get_context_data(self, **kwargs):
context = super(StatisticsView, self).get_context_data(**kwargs)
#logins = AuditEntry.objects.exclude(username='neuro')
count = AuditEntry.objects.filter(action='user_logged_in').exclude(username='demo').exclude(username='neuro').values('username').annotate(total=Count('username')).order_by('total')
#print(count)
usernames = []
counts = []
for c in count:
usernames.append(c['username'].encode('ascii','ignore'))
counts.append(c['total'])
print(usernames)
requests = RequestRequest.objects.filter(referer__icontains='/shops/rest_new/',response=200,path='/rest/pharmakeia/').exclude(user=None).exclude(user__username='demo').exclude(user__username='neuro').values('user__username').annotate(total=Count('user__username')).order_by('total')
print(requests)
usernames_r = []
counts_r = []
for r in requests:
usernames_r.append(r['user__username'].encode('ascii','ignore'))
counts_r.append(r['total'])
if self.request.POST:
self.date_year = self.request.POST['date_year']
self.date_month = self.request.POST['date_month']
monthform = DateMonthForm(self.request.POST or None)
context ['form'] = monthform
context['counts_r'] = counts_r
context['usernames_r'] = mark_safe(usernames_r)
context['counts'] = counts
context['usernames'] = mark_safe(usernames)
#context['logins'] = logins
return context
小部件.py
from django.forms.widgets import TextInput, DateInput, DateTimeInput, TimeInput
import datetime
import re
from django.conf import settings
from django.forms.widgets import Widget, Select
from django.utils.dates import MONTHS
from django.utils.safestring import mark_safe
class MyEmailInput(TextInput):
input_type = 'email'
class MyNumberInput(TextInput):
input_type = 'number'
class MyTelephoneInput(TextInput):
input_type = 'tel'
class MyDateInput(DateInput):
input_type = 'date'
format_key = 'DATE_INPUT_FORMATS'
class MyDateTimeInput(DateTimeInput):
input_type = 'datetime'
class MyTimeInput(TimeInput):
input_type = 'time'
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+3)
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, basestring):
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 = 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 datetime.date(int(y), int(m), 1).strftime( settings.DATE_INPUT_FORMATS[0] )
我的回溯
Environment:
Request Method: GET
Request URL: .../logging/
Django Version: 1.11.16
Python Version: 2.7.12
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'intranet',
'bootstrap3',
'registration',
'crispy_forms',
'fm',
'dal',
'dal_select2',
'rest_framework',
'django_filters',
'django_crontab']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template /var/www/vhosts/maps.karabinismedical.gr/geolocator/templates/base.html, error at line 0
build_attrs() got an unexpected keyword argument 'id' 1 : {% load i18n %}
2 : {% load static %}
3 : {% load staticfiles %}
4 : <!DOCTYPE html>
5 : <html lang="en">
6 : <head>
7 :
8 : <meta charset="utf-8">
9 : <meta name="viewport" content="width=device-width, initial-scale=1.0">
10 : <style>
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
217. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
215. response = response.render()
File "/usr/local/lib/python2.7/dist-packages/django/template/response.py" in render
107. self.content = self.rendered_content
File "/usr/local/lib/python2.7/dist-packages/django/template/response.py" in rendered_content
84. content = template.render(context, self._request)
File "/usr/local/lib/python2.7/dist-packages/django/template/backends/django.py" in render
66. return self.template.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
207. return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in _render
199. return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
990. bit = node.render_annotated(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render
177. return compiled_parent._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in _render
199. return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
990. bit = node.render_annotated(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render
72. result = block.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
990. bit = node.render_annotated(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/library.py" in render
203. output = self.func(*resolved_args, **resolved_kwargs)
File "/usr/local/lib/python2.7/dist-packages/bootstrap3/templatetags/bootstrap3.py" in bootstrap_form
338. return render_form(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/bootstrap3/forms.py" in render_form
53. return renderer_cls(form, **kwargs).render()
File "/usr/local/lib/python2.7/dist-packages/bootstrap3/renderers.py" in render
87. return mark_safe(self._render())
File "/usr/local/lib/python2.7/dist-packages/bootstrap3/renderers.py" in _render
230. return self.render_errors(self.error_types) + self.render_fields()
File "/usr/local/lib/python2.7/dist-packages/bootstrap3/renderers.py" in render_fields
194. bound_css_class=self.bound_css_class,
File "/usr/local/lib/python2.7/dist-packages/bootstrap3/forms.py" in render_field
69. return renderer_cls(field, **kwargs).render()
File "/usr/local/lib/python2.7/dist-packages/bootstrap3/renderers.py" in render
87. return mark_safe(self._render())
File "/usr/local/lib/python2.7/dist-packages/bootstrap3/renderers.py" in _render
551. html = self.field.as_widget(attrs=self.widget.attrs)
File "/usr/local/lib/python2.7/dist-packages/django/forms/boundfield.py" in as_widget
127. **kwargs
File "/var/www/vhosts/maps.karabinismedical.gr/geolocator/intranet/widgets.py" in render
77. local_attrs = self.build_attrs(id=self.month_field % id_)
Exception Type: TypeError at /logging/
Exception Value: build_attrs() got an unexpected keyword argument 'id'
解决方案
最后我找到了修复答案。在我的小部件中,我必须更改代码如下:
local_attrs=self.attrs
local_attrs['id'] = self.year_field % id_
s = Select(choices=month_choices)
select_html = s.render(self.month_field % name, month_val, local_attrs)
output.append(select_html)
推荐阅读
- javascript - 从 JSON 模式生成 JavaScript 类
- javascript - 如何在量角器 e2e 测试中等待浏览器?
- c - 当我打印新值时,我得到了以前的浮点值
- c# - 从不同项目的 appsettings.json 读取多个连接字符串
- macos - 如何在 shell 脚本中确定 Mac OS X 版本?
- javascript - 选择下拉列表首先显示最后一个值
- javascript - 内联箭头函数点击监听器
- jsp - 是否可以使用 .jsp 网页在 solr 中导入 csv 文件?
- sql - 如何从Oracle中的句子中删除符号?
- node.js - 使用/在 Shibboleth 身份验证后进行的数据库身份验证