[Python] Flask Route and JS Script Are Not Working

Discussão em 'Python' iniciado por Stack, Fevereiro 12, 2025.

  1. Stack

    Stack Membro Participativo

    I have a Flask app that calls an alert using JS in a route. The alert never pops up when I go to the route from the home page. The only time it works is when it is rendered from the get go (localhost:5000/register) or refreshed by the browser (/register). Why wont the alert work from the Flask home route when clicked. It seems simple enough. Here is the set up:

    app.py:

    from app import create_app
    app = create_app()
    if __name__ == "__main__":
    app.run(debug=True)


    routes.py:

    from flask import Blueprint, render_template
    routes_bp = Blueprint('routes', __name__, url_prefix="/")

    @routes_bp.route('/')
    def home():
    return render_template('home.html')

    @routes_bp.route('/register')
    def register():
    return render_template('register.html')


    init.py:

    from flask import Flask
    from app.routes import routes_bp

    def create_app():
    app = Flask(__name__ )
    app.register_blueprint(routes_bp)
    return app


    base.html:

    <html>
    <body>
    <div>
    {% block body %}{% endblock %}
    </div>

    <script src="{{ url_for('static', filename='js/client.js') }}" defer></script>
    // above works when load page first time , using refresh button on browser, this file doesn't render in home either
    </body>
    </html>


    home.html:

    {% extends "base.html" %}

    {% block body %}
    <a href="{{ url_for('routes.register') }}"> Register</a>
    <a href="{{ url_for('routes.login') }}"> Login</a>
    {% endblock %}


    register.html:

    {% extends "base.html" %}

    {% block body %}
    html here ...
    <script type="text/javascript"> alert('hello')</script>
    // alert does not work when I click route from home.html, does work when I refresh URL from browser
    {% endblock %}


    Directory structure is:

    - app
    -- init.py
    -- routes.py
    -- static
    --- js
    ---- custom.js
    -- templates
    --- base.html
    --- home.html
    --- register.html
    - app.py

    Continue reading...

Compartilhe esta Página