Search code examples
pythonpyramidhtml-selectmako

Pyramid "select" form input raise a KeyError


I am trying to access a request.param in my Pyramid application.

I saw a topic about checkboxes, but nobody talked about the "select" HTML tag.

On the pyramid view side, here is the part of my code which gathers the parameters:

if 'form.submitted' in request.params: # user
    user = User(request.params['nickname'],
                request.params['lastname'],
                request.params['firstname'],
                request.params['email'],
                request.params['password'],
                request.params['profile'])

On the Mako template side, my form is a simple HTML statement:

<select name="profile">
    % for profile in p:
        % if profile is u.profile:
            <option selected>${profile.name}</option>
        % else:
            <option>${profile.name}</option>
        % endif
    % endfor
</select>  

Every time I try to reach the 'profile' parameter, I got a KeyError... exception.

Can anyone help me to solve this?


UPDATE: I can't get the KeyError Mako was throwing this morning... Maybe my co-worker fixed this, I need to check the last commits. Now the user is created the good way, but when I redirect the application user to the same form (with a validation message), I can't display the good in the statement. Sorry for the inconvenience...


Solution

  • Difficult to tell for sure without seeing what exactly is returned from the view, but if a key error is being thrown in mako, it usually means you are not returning that parameter from the view. For example:

    @view_config(route_name='myform', renderer='myform.mako')
    def myform(request):
       if request.POST:
           # do stuff with submitted form ...       
       user ={'name': 'bob'}
       return {'user': user}
    

    within myform.mako you can access user.name, but a key error is thrown if you try to access user.profile.