我有MyModel
如下所列的模型。当我提交表单时/
,我得到了一个KeyError
异常/add
值name
。根据调试器,错误在这一行中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
保存功能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)