我试图减少代码,使其不会过于混乱。我想从 html 表单中接收重复的次数,并创建与标识的用户一样多的条目。如果用户在“月”输入字段中说 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'