user14915099
user14915099

Reputation:

Flask, url_for() not linking static file

I'm having trouble linking my static "css" file. When I run the code I only get my basic html and not the css. When I use the html element all of my css code work fine. Here is my code:

h1 {
  padding: 60px;
  text-align: center;
  background: #1abc9c;
  color: white;
  font-size: 30px;
}

.header {
  padding: 60px;
  text-align: center;
  background: #1abc9c;
  color: white;
  font-size: 30px;
}

.sidebar {
  height: 200px;
  width: 150px;
  position: sticky;
  top: 0px;
  float: right;
  margin-top: 100px;
  padding-top: 40px;
  background-color: lightblue;
}

.sidebar div {
  padding: 8px;
  font-size: 24px;
  display: block;
}

.body-text {
  margin-right: 150px;
  font-size: 18px;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta charset="UTF-8">
  <link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
</head>


<body>
  <h1>Header</h1>


  <div class="sidebar">
    <div>Menu Item 1</div>
    <div>Menu Item 2</div>
    <div>Menu Item 3</div>
  </div>

  <div class="body-text">
    <!-- body content -->
  </div>
</body>

</html>

Here is my python code also in case that is causing a problem:

from flask import Flask, render_template, redirect, url_for

app = Flask(__name__)

app.config['ENV'] = 'development'
app.config['DEBUG'] = True
app.config['TESTING'] = True

app.static_folder = 'static'

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

@app.route('/<name>')
def user(name):
    return f"Hello {name}!"

@app.route('/admin')
def admin():
    return redirect(url_for('index', name='Admin'))

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

Thanks for any help. Sorry if the code is messy, I'm a rookie :).

Upvotes: 0

Views: 929

Answers (2)

Gitau Harrison
Gitau Harrison

Reputation: 3517

This may be an issue with the structure of your application. Consider this structure:

project_folder
   | --- app/
          | --- templates/
                 | --- index.html
          | --- static/
                 | --- style.css

The templates sub-folder should be at the same location as the static sub-folder. Your link should work just with this structure.

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">

Upvotes: 0

Tim
Tim

Reputation: 73

In addition to the answer given above, this might also occur sometimes if your browser has already cached the CSS file. You can force your browser to refresh the contents using Ctrl+f5 on your keyboard each time you add new code in your style.css file.

Upvotes: 1

Related Questions