user592419
user592419

Reputation: 5233

Flask URL Routing

If I'm making a blog site and I want to set up routing such that

@app.route('/<username>/<postname>', methods=['GET']) 

routes to the post with name 'postname' of the user with name 'username', how do I get the html to recognize this? I've been trying to do something like

<a href={{ url_for('/', username=user.name, postname=post.name) }}>{{post.name}}</a>

I'm also trying to reconcile this with Flask understanding special keywords /login or /about so that it checks if the user is trying to access those first. How can I implement those checks?

Upvotes: 2

Views: 1595

Answers (1)

Blender
Blender

Reputation: 298552

The first argument to url_for in your template should be the name of the view function you decorated:

@app.route('/<username>/<postname>', methods=['GET'])
def view_user_post(username, postname):
    ^^^^^^^^^^^^^^

Now, you can write this in your template:

{{ url_for('view_user_post', username=user.name, postname=post.name) }}

This lets you change the URL in the route without having to update it elsewhere in your codebase.

Upvotes: 4

Related Questions