0

我试图减少代码,使其不会过于混乱。我想从 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'
4

2 回答 2

3

问题是您正在返回包含循环中第一项的响应。

让我隔离这个for循环..在底部注意它立即退出循环。

                line = LineItem(
                name    = form.cleaned_data['name'],
                date    = date.today() + relativedelta(months=m),
                )
                line.save()
                return HttpResponseRedirect('/lines')
于 2013-08-31T04:36:21.253 回答
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()-creation 循环中使用它们。

于 2013-08-31T17:57:01.950 回答