msampaio
msampaio

Reputation: 3433

Django form request KeyError

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?

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)

templates/main.html

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

templates/add.html

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

Edition 1

myproject/settings.py (template context processors)

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

Edition 2 - solved

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

Answers (1)

Daniel Roseman
Daniel Roseman

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

Related Questions