Creating Dynamic URLs in Flask Web Framework

Posted by


In Flask, you can dynamically build URLs using the url_for() function. This function allows you to generate URLs for specific view functions based on their names. This can be particularly useful when you have multiple routes in your Flask application and you want to avoid hardcoding URLs in your templates or code.

To demonstrate how to dynamically build URLs in Flask, let’s create a simple application with two routes: one for the homepage and one for a user profile page.

First, make sure you have Flask installed. You can install it using pip:

pip install Flask

Next, create a new Python file for your Flask application. Let’s name it app.py.

from flask import Flask, render_template, url_for

app = Flask(__name__)

@app.route('/')
def homepage():
    return render_template('index.html')

@app.route('/user/<username>')
def profile(username):
    return f'Hello, {username}!'

if __name__ == '__main__':
    app.run(debug=True)

In this code, we have defined two routes: one for the homepage (/) and one for a user profile page (/user/<username>). The profile view function takes a username parameter, which is used to customize the message displayed on the page.

Now, let’s create the index.html template file in a templates folder in the same directory as app.py. This file will contain a link to the user profile page.

<!DOCTYPE html>
<html>
<head>
    <title>Homepage</title>
</head>
<body>
    <h1>Welcome to the Homepage!</h1>
    <a href="{{ url_for('profile', username='john') }}">Visit John's profile</a>
</body>
</html>

In this template, we use the url_for() function to generate the URL for the profile route with the username parameter set to "john". This way, the link will dynamically point to the profile page for the user "john".

Finally, run your Flask application by executing python app.py in the terminal. You should see a message indicating that the application is running. Open a web browser and navigate to http://127.0.0.1:5000 to view the homepage. Click on the link to visit John’s profile page.

By using the url_for() function in Flask, you can easily build URLs dynamically in your web application. This can help you avoid hardcoding URLs and make your code more flexible and maintainable.

0 0 votes
Article Rating

Leave a Reply

31 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@abdulmoizasif3930
26 days ago

10:55, when redirecting using url_for, does the first parameter have to be the function name or the url title, for instance if I had url /success but my function name is not success then it doesn't work so is it using the function name primarily?

@mehdismaeili3743
26 days ago

Excellent .

@JacklinSibiyal
26 days ago

Day 9 – 02/03/24

@sankhasubhrachatterjee5069
26 days ago

Thank you very much for this video. Can you please show us how to debug this ?

@PrateekMathur-s6q
26 days ago

@krish Naik Sir, how to redirect if we have multiple path vairables, like score is one, if we have more than one, how to handle that? please explain for both, redirect+url_for AND routing

@sudhirs003
26 days ago

@krish if we enter single digit, say instead of 30, I mentioned 3, it gives 30. I am missing anything here?

@deepgupta234
26 days ago

Superb

@nadeemyousuf4332
26 days ago

My server is not getting updated after i search for server/success/55 shows server not found ?

@BlinkCodee
26 days ago

PREVIOUSLY FLASK HAS RENDER_TEMPLTE WHICH IS NOT WORKING RIGHT NOW WHY I DONT KNOW:

@harishreports
26 days ago

Thanks

@VR-fh4im
26 days ago

Why are you scrolling up and down so frequently? Hold the screen in one place, it is so distracting.

@sujangajananachari2814
26 days ago

if i make any changes in flask it won't update when i use debug=True, please anyone help me to solve this issue @krish naik

@kavyamaddu9332
26 days ago

Thanks for your video. It is very helpful .
By default it is taking 5000 port and default ip.
If I want some specific ip and port then how to do that.
Can you please let me know the details

@ShubhamSingh-lx6fd
26 days ago

❤️❤️

@kaladharmurakonda9233
26 days ago

I want give my member ship.how pay canby atm card

@nimeshkumar9564
26 days ago

Thankyou sir.😄

@vigneshaithal
26 days ago

Helped a lot for my hackathon. Thanks a lot sir.

@rushabhbobade527
26 days ago

Which study material should i preferred for flask??

@indranildreams
26 days ago

You make my day Krish, I am your Full stack Data Science Student, I do not have PyCharm & only the way I can do using VS Code in my Office Laptop..In VSCode I was struggling to use Flask but your easiest video make life so easy and build First Flask Code..Thank you so Much 🙂

@louerleseigneur4532
26 days ago

Thanks Krish

31
0
Would love your thoughts, please comment.x
()
x