1

我有MyModel如下所列的模型。当我提交表单时/,我得到了一个KeyError异常/addname。根据调试器,错误在这一行中views.form_add

name = request.session['name']

怎么了?

myapp/models.py

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

我的应用程序/forms.py

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

我的应用程序/urls.py

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

我的应用程序/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)
4

1 回答 1

1

这是非常奇怪的代码。当您的表单提交时,如果它是有效的,您将name值放入一个变量中,该变量会立即被丢弃。您不保存表单,而是再次丢弃这些值。无论表单是否有效,您都会立即重定向到add/URL,在该 URL 中假设name会话中有一个值,尽管之前从未将任何内容保存到会话中。

您的基本问题是会话中没有name密钥,但是鉴于您显示的代码,我对您为什么认为会有密钥感到困惑。

于 2012-09-28T19:49:56.400 回答