ffuentes
ffuentes

Reputation: 1182

Optional URL parameter on Pyramid route

For example I want to use the same route to submit a form and to show the content of forms based on their id number.

I thought a rematched parameter:

config.add_route('poll', '/poll/{id}*')

was enough but it doesn't work. When the method POST finishes I want it to load the page showing the result but it throws a 404 error.

Upvotes: 1

Views: 1628

Answers (1)

Michael Merickel
Michael Merickel

Reputation: 23331

From http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/urldispatch.html#route-pattern-syntax:

config.add_route('poll', '/poll/{id:.*}')

Note that when generating a url via request.route_url('poll', id='5') the id parameter is required, you cannot leave it out. You can solve this with a pregenerator:

def pregen(request, elements, kw):
    kw.setdefault('id', '')
    return elements, kw
config.add_route('poll', '/poll/{id:.*}', pregenerator=pregen)

This will allow you to use request.route_url('poll') as well as request.route_url('poll', id='5').

Upvotes: 6

Related Questions