我的模型MyModel
如下所示。当我在/
中提交表单时,我在KeyError
获得/add
,异常值为name
。根据调试器,错误在views.form_add
:
name = request.session['name']
有什么问题?
class MyModel(models.Model):
name = models.CharField(max_length=50)
class MyModelForm(ModelForm):
class Meta:
model = MyModel
urlpatterns = patterns('myapp.views',
url(r'^$', 'main'),
url(r'^add/', 'form_add'),
)
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)
<form method="POST" id="" action="">
{% csrf_token %}
{{ form.as_p }}
<button>Submit</button>
</form>
<p>{{ name }}</p>
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.core.context_processors.static',
)
我重写了我的main
功能保存MyModel
和request.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)
答案 0 :(得分:1)
这是非常奇怪的代码。提交表单后,如果表单有效,则将name
值放在变量中,该变量立即被丢弃。您不保存表单,但再次丢弃值。无论表单是否有效,您都会立即重定向到add/
网址,您可以假设会话中存在name
值,尽管之前从未向会话保存任何内容。
您的基本问题是会话中没有name
键,但考虑到您显示的代码,我对您认为存在的原因感到困惑。