[英]ValueError with Django form initial
I'm building a reservation app with Django
and I want to allow users to use one reservation as template for another. 我正在使用
Django
构建预订应用程序,并且希望允许用户将一个预订用作另一个预订的模板。 My idea is that I add ?prefill=<reservation_id>
to url and then prefill empty form with data from reservation in prefill
id. 我的想法是,将
?prefill=<reservation_id>
添加到url,然后用预prefill
ID中的保留数据预填充空表格。
My CreateView
looks like this: 我的
CreateView
看起来像这样:
class ReservationCreateView(LoginRequiredMixin, CreateUpdateMixin, CreateView):
model = Reservation
form_class = ReservationForm
success_url = '/'
def get_context_data(self, **kwargs):
ctx = super(ReservationCreateView, self).get_context_data()
r = Reservation.objects.filter(pk=self.request.GET.get('prefill'))
ctx['form'] = ReservationForm(initial=r.values(), request=self.request)
return ctx
This gives me: dictionary update sequence element #0 has length 30; 2 is required
这给我:
dictionary update sequence element #0 has length 30; 2 is required
dictionary update sequence element #0 has length 30; 2 is required
Error stack: 错误堆栈:
Environment:
Request Method: GET
Request URL: http://localhost:8000/r/create/?prefill=56cc36bd-c766-4e45-8a1b-cdde3cd87dc4
Django Version: 1.10.3
Python Version: 2.7.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'tags',
'profiles',
'reservations',
'drivers',
'import_export',
'src',
'crispy_forms',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'anymail',
'wf',
'storages',
'djangoformsetjs']
Installed Middleware:
['corsheaders.middleware.CorsMiddleware',
'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',
'htmlmin.middleware.HtmlMinifyMiddleware',
'htmlmin.middleware.MarkRequestMiddleware']
Traceback:
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/contrib/auth/mixins.py" in dispatch
56. return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/reservations/mixins.py" in get
68. route_formset=route_formset))
File "/Users/jhotujec/Documents/projects/optilimo/reservations/views.py" in get_context_data
108. ctx['form'] = ReservationForm(initial=r.values(), request=self.request)
File "/Users/jhotujec/Documents/projects/optilimo/reservations/forms.py" in __init__
30. super(ReservationForm, self).__init__(*args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/forms/models.py" in __init__
285. object_data.update(initial)
Exception Type: ValueError at /r/create/
Exception Value: dictionary update sequence element #0 has length 30; 2 is required
The problem is initial=r.values()
where r
is a QuerySet
. 问题是
initial=r.values()
,其中r
是QuerySet
。 values
returns a list of dicts
, initial
expects a dict
. values
返回一个dicts
列表, initial
期望一个dict
。 You could get the Reservation
instance and use the instance
parameter of the form constructor instead: 您可以获取
Reservation
实例,而使用表单构造函数的instance
参数:
# first() will return None if the QS is empty
r = Reservation.objects.get(pk=self.request.GET.get('prefill')).first()
ctx['form'] = ReservationForm(instance=r, request=self.request)
filter()
always returns a queryset, and values()
is then basically a list of dicts, whereas the form is expecting a single dict. filter()
总是返回一个查询集,然后values()
基本上是字典列表,而该表单只需要一个字典。
You could fix this by using r.values()[0]
instead, but this is really the wrong approach. 您可以改用
r.values()[0]
修复此问题,但这确实是错误的方法。 This is a model form; 这是一个模型形式; you should populate it by passing an actual model instance as the
instance
argument. 您应该通过传递实际的模型实例作为
instance
参数来填充它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.