Django表单请求KeyError

时间:2012-09-28 19:31:49

标签: django django-forms django-views

我的模型MyModel如下所示。当我在/中提交表单时,我在KeyError获得/add,异常值为name。根据调试器,错误在views.form_add

中的这一行
name = request.session['name']

有什么问题?

的myapp / models.py

class MyModel(models.Model):
    name = models.CharField(max_length=50)

的myapp / forms.py

class MyModelForm(ModelForm):
    class Meta:
        model = MyModel

的myapp / urls.py

urlpatterns = patterns('myapp.views',
    url(r'^$', 'main'),
    url(r'^add/', 'form_add'),
)

的myapp / views.py

def main(request):
    if request.method == 'POST':
        form = MyModelForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
        return HttpResponseRedirect('/add') # Redirect after POST
    else:
        form = MyModelForm()
        args = {}
        args['form'] = form
    return render(request, 'main.html', args)

def form_add(request):
    args = {}
    name = request.session['name']
    args['name'] = name
    mm = MyModel(name=name)
    mm.save()

    return render(request, 'add.html', args)

模板/ main.html中

<form method="POST" id="" action="">
  {% csrf_token %}
  {{ form.as_p }}
  <button>Submit</button>
</form>

模板/ add.html

<p>{{ name }}</p>

第1版

myproject / settings.py(模板上下文处理器)

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.contrib.messages.context_processors.messages',
    'django.core.context_processors.static',
    )

第2版 - 解决了

我重写了我的main功能保存MyModelrequest.session['name'],如下所示。

def main(request):
    if request.method == 'POST':
        form = MyModelForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            # I added the lines below to create MyModel and request
            request.session['name'] = name
            mm = MyModel.objects.create(name=name)
            mm.save()
            # the indentation was wrong
            return HttpResponseRedirect('/add') # Redirect after POST
    else:
        form = MyModelForm()
    # the indentation was wrong
    args = {}
    args['form'] = form
    return render(request, 'main.html', args)

1 个答案:

答案 0 :(得分:1)

这是非常奇怪的代码。提交表单后,如果表单有效,则将name值放在变量中,该变量立即被丢弃。您不保存表单,但再次丢弃值。无论表单是否有效,您都会立即重定向到add/网址,您可以假设会话中存在name值,尽管之前从未向会话保存任何内容。

您的基本问题是会话中没有name键,但考虑到您显示的代码,我对您认为存在的原因感到困惑。