andrrrify
andrrrify

Reputation: 33

Flask URL path not working

I began creating an extremely simple Flask application as I've done before and I'm getting a 404 error that's going completely over my head. My directory structure is as follows:

Site/
----static/
--------css/
------------css files
--------img/
------------image files
----templates/
--------contact.html
--------index.html
app.py

The problem I'm having is that there is a button within the index.html page that takes you to the contact.html page.

<nav class="main-nav">
        <ul>
            <li>
                <a href="#">Home</a>
            </li>
            <li>
                <a href="#">About Me</a>
            </li>
            <li>
                <a href="#">Resume</a>
            </li>
            <li>
                <a href="contact.html">Contact</a>
            </li>
        </ul>
    </nav>

This button takes you to the contact page which works exactly as it should when I'm using Live Server in VSCode. The problem is when I try to go to this page in the Flask local server. Here is app.py:

from flask import Flask, render_template

app = Flask (__name__)
app.debug = True

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

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



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

I've always followed this basic syntax for routing to pages and it's always worked until now and I can't figure out why I get a 404 error. I've tried leaving a trailing space in the app.route and clearing my browsers cache in case its a redirect error and still nothing. When I open the contact page in Live Server and Flask and place them next to each other they have the exact same url just on different localhost ports. What am I missing?

Upvotes: 1

Views: 7337

Answers (3)

Robᵩ
Robᵩ

Reputation: 168876

Your route is named contact, but your link is to contact.html. Those names need to be identical.

Try one of these:

@app.route('/contact.html')

OR

<a href="contact">Contact</a>

As was pointed out elsewhere, the recommended usage is url_for():

<a href={{url_for('contact')}}>Contact</a>

Upvotes: 2

George Pamfilis
George Pamfilis

Reputation: 1507

Do not use the contact.html only the route name as follows.

<a href="{{ url_for('app.contact') }}">Contact</a>

meaning...

<a href=" {{ url_for('blueprint_name.route_name') }}">Route</a>

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71471

You do not need to provide a file name in href route:

<a href="/contact">Contact</a>

Upvotes: 1

Related Questions