我试图削减代码,以免它过于混乱。 我希望从html表单中接收重复次数,并创建与标识的用户一样多的条目。在这里,我想说make,如果用户在“月份”输入字段中显示12,则连续12次付款
template.html:
<form action="" method="post">
Name: {{ form.name }}
Date: {{ form.date }}
<input type="text" alt="months" name="months">
<input type="submit" alt="register" class="" value="Submit"/>
</form>
views.py
if request.method == "POST":
form = CreateForm(request.POST)
if form.is_valid():
months = range(int(form.cleaned_data['months']))
for m in months:
line = LineItem(
name = form.cleaned_data['name'],
date = date.today() + relativedelta(months=m),
)
line.save()
return HttpResponseRedirect('/lines')
else:
pass
else:
pass
我得到了一个KeyError,如果我取出int(),我只得到1个条目,但不是12或者任何规定的数字。
class CreateForm(ModelForm):
class Meta:
model = LineItem
fields= ('name','date')
widgets = {
'date': DateInput()
}
修改:添加表单,修复语法,追溯
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/lines/
Django Version: 1.4.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'bet',
'love')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/Patrick/Dropbox/CrushFolder/tenant/love/views.py" in LinesAll
33. months = range(form.cleaned_data['months'])
Exception Type: KeyError at /lines/
Exception Value: 'months'
答案 0 :(得分:3)
问题是您正在使用循环中的第一个项目返回响应。
让我将其隔离为循环..注意在底部它会立即退出循环。
line = LineItem(
name = form.cleaned_data['name'],
date = date.today() + relativedelta(months=m),
)
line.save()
return HttpResponseRedirect('/lines')
答案 1 :(得分:1)
"months"
不是由表单验证或检查的字段。这将解决您的直接问题:
if form.is_valid():
# change:
#months = range(int(form.cleaned_data['months']))
# to:
months = range(int(request.POST['months']))
但更大的图片:你不应该使用ModelForm
。 A),它是不必要的复杂性,B),这实际上不是用户设置用于创建LineItem
实例的属性的表单。相反,这是一个表单,您可以获取数据然后用于驱动实际构建LineItem
实例的应用程序逻辑,并生成值(即,连续的月份偏移日期) )。丢失ModelForm,使用“name”和“months”字段执行常规表单,然后form.cleaned_data
将包含您期望的项目("name"
和"months"
),您可以然后在LineItem()
- 创建循环中使用。