I am a beginner at web development. I am using Python and Django on a Mac. When I want to link CSS to HTML, this shows in the command line and on the web page is still only text from the html file.
Command line:
Not Found: /style.css
[29/May/2021 17:37:12] "GET /style.css HTTP/1.1" 404 2095
This is my HTML file:
<html>
<head>
<title>Webpage</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<p>Webpage</p>
</body>
</html>
and this is my CSS file:
body {
background-color: royalblue;
}
Your static file is not matching any URL pattern rule. Configure static files from here, and also configure urls.py from here for development
This may be because you do not have your CSS file in the same relative directory as the file you're working on.
If you have the CSS file in the root of your server directory, you may need to add / to the beginning of your path.
An example is if your directory structure looks like this
.
├── homepage.html
├── index.html
├── other
│ └── test.html <-- The page you are accessing
└── style.css
If in this page, you had <link rel="stylesheet" href="style.css">, it would not work, since style.css is not in the other/ directory.
That is because, unless you specify, all the paths are relative.
You can specify that you do not want relative paths by adding / to the beginning of your path followed by the directory that style.css is located in.
<link rel="stylesheet" href="/styles/style.css">
The / ensures that this will work in any file in the HTML directory
My folder layout is:
/env
app.py
/env/static/styles
main.css
/env/static/img
contains all the image
/env/templates
index.html
My main.css contains:
#background_section_top {
width: 100%;
height:88px;
background: url(static/img/background_section_top_bg.jpg);
background-repeat: repeat-x;
}
My index.html contains:
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/main.css') }}">
But I couldn't see the image in my index.html. Could you please help where I'm doing mistake? Thanks.
Just modify
background: url(static/img/background_section_top_bg.jpg);
to
background: url(/static/img/background_section_top_bg.jpg);
I am trying to create a website using Flask, but while my HTML file is working, my CSS file is not working. I have tried refreshing my cache and using different lines of code others have posted on similar questions, but nothing has worked for me.
This is my current project hierarchy:
I have the following line of code in my HTML file's head.
<link rel="stylesheet" href="{{ url_for('static', filename='css/mainpage.css') }}">
I got this code from a different stack overflow question too, so I am quite confused on what I am doing wrong too.
Application not picking up .css file (flask/python)
Thanks in advance!
I could not duplicate your problem with the following toy example:
#!venv/bin/python
from flask import Flask
from flask import render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
My directory layout is
├── app.py
├── static
│ └── css
│ └── mainpage.css
├── templates
│ └── index.html
└── venv
The contents of index.html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="{{ url_for('static', filename='css/mainpage.css') }}">
<title>Page Title</title>
</head>
<body>
<h1>Page Heading</h1>
<p>A paragraph.</p>
</body>
</html>
The contents of mainpage.css:
body {
background-color: powderblue;
}
h1 {
color: blue;
}
p {
color: red;
}
Try adding the following piece of code in the head section
<link rel="stylesheet" type="text/css" href="/static/css/mainpage.css">
I'm new to web dev and am working on my first fully custom site built with Flask. I used HTML5 Boilerplate for the base code structure and Jinja to template my pages. Here is the file structure:
.
├── app
│ ├── __init__.py
│ ├── forms.py
│ ├── static
│ │ ├── browserconfig.xml
│ │ ├── crossdomain.xml
│ │ ├── css
│ │ │ ├── main.css
│ │ │ └── normalize.css
│ │ ├── img
│ │ │ ├── apple-touch-icon.png
│ │ │ ├── favicon.ico
│ │ │ ├── tile-wide.png
│ │ │ └── tile.png
│ │ ├── js
│ │ │ ├── main.js
│ │ │ ├── plugins.js
│ │ │ └── vendor
│ │ │ ├── jquery-1.12.0.min.js
│ │ │ └── modernizr-2.8.3.min.js
│ │ └── robots.txt
│ ├── templates
│ │ ├── 404.html
│ │ ├── about.html
│ │ ├── base.html
│ │ └── index.html
│ └── views.py
├── config.py
├── profile.py
├── run.py
├── tests.py
└── tmp
└── tmp.log
Here is what base.html looks like:
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>{{ title }}</title>
<meta name="description" content="{{ description }}">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link rel="/static/img/apple-touch-icon" href="/static/img/apple-touch-icon.png">
<!-- Place favicon.ico in the root directory -->
<link rel="stylesheet" href="/static/css/normalize.css" type="text/css">
<link rel="stylesheet" href="/static/css/main.css" type="text/css">
<script src="/static/js/vendor/modernizr-2.8.3.min.js"></script>
</head>
<body>
<!--[if lte IE 9]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please upgrade your browser to improve your experience and security.</p>
<![endif]-->
<!-- Add your site or application content here -->
<div class="header">
<div class="container">
<ul class="navigation">
<li>Home</li>
<li>About</li>
</ul>
</div>
</div>
{% block content %}{% endblock %}
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>window.jQuery || document.write('<script src="/static/js/vendor/jquery-1.12.0.min.js"><\/script>')</script>
<script src="/static/js/plugins.js"></script>
<script src="/static/js/main.js"></script>
<!-- Google Analytics: change UA-XXXXX-Y to be your site's ID. -->
<!-- <script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='https://www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X','auto');ga('send','pageview');
</script> -->
</body>
</html>
And in the Author's custom styles section of main.css (html5 boilerplate source here) I've added these initial stylings:
* {
font-family: 'Roboto', sans-serif;
}
.navigation {
list-style-type: none;
margin: 0;
padding: 20px 0;
}
.navigation li {
display: inline;
font-family: 'Roboto', sans-serif;
font-weight: 400;
font-size: 12px;
margin-right: 25px;
text-transform: uppercase;
}
Except when I start the server and go to the site, none of the custom styling seems to be taking affect. Some part of the css is definitely working because the site doesn't look like raw html, but my custom styles are not being interpreted. Am I doing something wrong in the html template?
Any help is appreciated.
Thank you!
CSS RESET will help you. The actual problem that you have is in the web browser. They change the style attributes, fonts, margins, padding, and many other things by DEFAULT. To fix this, you can directly append the following code to your stylesheet that wasn't working as well as you expected:
Note: Append the CSS reset before you put your code.
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
/*Your own CSS code*/
I am trying to create pdf from html page using pdfkit inside Flask application, but I have troubles to load the static files (stylesheets) when using pdfkit.
I've tried to come up with minimal example. I've got this file structure
App
|_ static
| |- style.css
|_ templates
| |- base.html
|_ pdfs
| |- file.pdf
|_ application.py
Inside application.py:
import flask
import pdfkit
app = flask.Flask(__name__)
#app.route('/')
def index():
page = flask.render_template('base.html')
pdfkit.from_string(page, 'pdfs/file.pdf')
return page
#app.route('/download', methods=['POST'])
def download():
if flask.request.method == 'POST':
flask.send_from_directory(
directory='pdfs', filename='file.pdf', as_attachment=True)
else:
flask.redirect(flaks.url_for('index'))
if __name__ == '__main__':
app.run()
Stylesheet just adds red background to the td elements:
td {
background-color: red;
}
And finally the base.html:
<!DOCTYPE html>
<html>
<head>
<title>Test App</title>
<link href={{ url_for('static', filename='style.css') }} rel='stylesheet'>
</head>
<body>
<div id='to_pdf'>
<table>
<tr>
<th>Firstname</th>
</tr>
<tr>
<td>Jill</td>
</tr>
<tr>
<td>Eve</td>
</tr>
</table>
<form action='/download' method='POST'>
<button type="submit" value="Print" />PRINT</form>
</form>
</div>
</body>
</html>
Sorry for the loads of code, but it is actually pretty basic.
All I want is to have button, which once clicked downloads a pdf file (this pdf is html file converted to pdf.
It sort of works, but the console output is the following:
Loading pages (1/6)
Warning: Failed to load file:///static/style.css (ignore)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done
The problem
pdfkit, which basically invokes wkhtmltopdf cannot find the stylesheet files inside static folder. The application, where I have this problem is more robust, uses boostrap etc. and having the pdf output badly formatted is very undesirable..
Single CSS file
css = 'example.css'
pdfkit.from_file('file.html', css=css)
Multiple CSS files
css = ['example.css', 'example2.css']
pdfkit.from_file('file.html', css=css)
In your case try this:
css = "static/style.css"
page = flask.render_template('base.html')
pdfkit.from_string(page, 'pdfs/file.pdf', css=css)
return page
Your code results in a link that wkhtmltopdf tries to open as a regular file:
{{ url_for('static', filename='style.css') }}
becomes
/static/style.css
which wkhtmltopdf will look for at
file://static/style.css
Instead, add the _external=True flag to point it towards the file on the server:
{{ url_for('static', filename='style.css', _external=True) }}
results in (something like)
http://localhost:5000/static/style.css
Assuming your app has config.py file you can add this config value.
ABS_PATH_STATIC_FOLDER = "var/www/.." #here is an absolute path to static dir
Then specify css file by:
css = os.path.join(app.config['ABS_PATH_STATIC_FOLDER'], 'pdfstyle.css')
This will work if the css file is placed in static folder or any other folder
Then pass on css to pdfkit fromstring function
pdfkit.from_string(page, 'pdfs/file.pdf', css=css)