Reputation: 3433
I have model MyModel
as listed below. When I submit the form, in /
, I got aKeyError
at /add
with exception value name
. According to debugger, the error is in this line in views.form_add
:
name = request.session['name']
What is wrong?
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',
)
I rewrote my main
function saving MyModel
and request.session['name']
as below.
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)
Upvotes: 1
Views: 2230
Reputation: 599470
This is very strange code. When your form is submitted, if it is valid, you put the name
value in a variable which is immediately thrown away. You don't save the form, but again throw away the values. Whether or not the form is valid, you redirect immediately to the add/
URL, where you assume that there is a name
value in the session, despite never having saved anything to the session previously.
Your base problem is that there isn't a name
key in the session, but I'm confused about why you think there would be, given the code you've shown.
Upvotes: 1