CSS not rendering in FastAPI Jinja2Template - html

UPDATE: This solved. I didn't write the correct CSS!
I am trying to render a few things in HTML. Multiple things are causing problems but I've included the most basic part I want to get working. If I can get this to work, I can get the rest to work.
Very simple app structure:
app
api.py
static
styles.css
templates
index.html
This is the contents of index.html:
<html>
<h1>
Title here
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet">
</h1>
</html>
This the the CSS I'm using:
h1 {
color: red
text-align: center
}
Relevant code in api.py:
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
app = FastAPI()
templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="static"), name="static")
#app.get("/", response_class=HTMLResponse)
def read_mean_cpu(request: Request, device_id):
return templates.TemplateResponse("index.html", {"request": request}))
Any idea why the CSS isn't taking?

Related

HTML Docs Not Updating from CSS

I am using a CSS file to update my HTML in a Django app, but despite the fact that my "style.css" sheet is linked to the HTML file, there are no updates occuring.
"style.css" is in the same folder as my HTML document ("index.html"), but nothing is changing.
I've pasted my code below:
<head>
<link type="text/css" rel="stylesheet" href="style.css" media="screen"/>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
I know that the CSS and HTML files are linked, because when I hover over the "style.css"href, I can press CTRL + click, and "styles.css" opens in a new window.
I've been through four or five tutorials, tried to restarted the local server, moving "style.css" to its own folder "styles", and then changed href to href="styles/style.css" but it is still not working.
I'm using VSCode, and Windows 11.
you need config template section in django settings
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
be carefull to create static and templates directory in project root or any
place you want and set in "DIR" in TEMPLATES for templates and set static for static files for js and css file. in static directory you must put your js and css file also you can create directory inside static directory called "js" hold js files and create "css" directory inside static for css files.
now render yout html file in view like below
from django.shortcuts import render
def index_view(request):
return render(request, "index.html")
now in your template files you can load static files
<!DOCTYPE html>
<head>
{% load static %}
<script src="{% static 'app.js' %}"></script>
<title>Site</title>
</head>
<body>
<img src="{% static 'img.png' %}" alt="Mon image" />
{% block content %}{% endblock %}
</body>
</html>
in your html file you should add:
{% load static %}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link type="text/css" rel="stylesheet" media="screen" href="{% static 'styles/style.css' %}"/>
<title>Document</title>
</head>
you should add in your setting.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR / "static",
]
also you should declare your folder structure like this:
in your root project (where manage.py declared), static folder and in your static folder you should have styles and in your styles is your style.css file.
static/styles/style.css
Apparently it was just a cache issue. Clearing it took care of this, so I'm now clearing the cache every time I modify anything in the CSS Templates, which comes to clearing the cache basically everyday.

How can I make title bar dynamic on vuetify?

I see vuetify project have title bar. But the title in public/index.html. Outside src folder
So I had trouble making it dynamic. Every page must have different title. If it's same, it's very influential on SEO
My public/index.html like this :
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>test-vuetify</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#mdi/font#latest/css/materialdesignicons.min.css">
</head>
<body>
<noscript>
<strong>We're sorry but test-vuetify doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
How can I solve this problem? I want to make title on every page is different. According to page content
Hard to tell exactly what your constraints are from the question, but in case this helps anyone else make their Vuetify title bar dynamic...
In index.js, add some "meta" to the routes:
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const routes = [
{
path: '/page1',
name: 'page-1',
component: ...,
meta: {
title: 'Page 1'
}
},
{
path: '/page2',
name: 'page-2',
component: ...,
meta: {
title: 'Page 2'
}
}
]
const router = new VueRouter({
mode: 'history',
base: (your base url),
routes: routes,
});
export default router
Then in the Vuetify title bar, use the route meta defined above:
<v-toolbar-title>{{ $route.meta.title || "Default title" }}</v-toolbar-title>

Bokeh plot not showing in Flask

Problem: My Bokeh plot, implemented with Flask, is not showing in my browser. When I run the app, the Bokeh frame (with the tools), as well as the x-axis label show up, but no data is plotted inside.
Already tried: I've made sure that the Bokeh version mentioned in the HTML files is as others have suggested. I'm pretty sure I've exhausted the SO solutions presented already. I've used print statements throughout the program and determined that the data is actually collected, cleaned, and processed with the components module and passed to 'script'. So therefore, as far as I can tell, the code seems to be stuck at the 'last render_template line?
from flask import Flask, render_template, request, redirect, session
import pandas as pd
import quandl
from bokeh.plotting import figure, output_file, save
from bokeh.embed import components
from bokeh.io import show
app = Flask(__name__) #create an instance of the flask class (named 'app') in the current file
app.vars={}
#app.route('/')
def main():
return redirect('/index')
#app.route('/index', methods=['GET'])
def index():
return render_template('index.html')
#app.route('/plot', methods=['POST'])
def plot():
app.vars['current_symbol'] = request.form['current_symbol']
quandl.ApiConfig.api_key = 'CD38JS9JqAdmdeio9JPW'
req_data = quandl.get_table('WIKI/PRICES', ticker=app.vars['current_symbol'], qopts = {'columns':['ticker', 'date', 'adj_close']}, date = {'gte': '2017-11-01', 'lte': '2017-12-01'}, paginate = True)
req_data.adj_close = round(req_data.adj_close, 2)
req_data = req_data.set_index('date')
cleaned_data = req_data.pivot(columns = 'ticker')
# Plot the data
p = figure(x_axis_type='datetime', x_axis_label='Date', y_minor_ticks=2, plot_width = 800, plot_height = 600)
p.line(x = cleaned_data.index, y = cleaned_data.adj_close, line_width = 2)
script, div = components(p)
return render_template('plot.html', script=script, div=div)
if __name__ == "__main__":
app.run(debug=True)
Here are the accompanying HTML files.
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Stock Plotter</title>
<link href="https://cdn.bokeh.org/bokeh/release/bokeh-1.2.0.min.css" rel="stylesheet" type="text/css">
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-1.2.0.min.js"></script>
<!-- <link rel="icon" href="favicon.ico"> -->
<title>Stock Plotter</title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class=metanav>
<h1>Stock Plotter</h1>
<div>
<form id="tickerform" action="/plot" method="POST">
Ticker Symbol: <input type="text" name="current_symbol" placeholder="ticker symbol"></input> <!--Create a dropdown list with the following options=-->
<div>
<input type="submit" value="Submit"></input> <!--Create the submit button-->
</div>
</form>
</div>
{{ script|safe }} <!--Marks the js scrips as safe for the web-->
{{ div|safe }}
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
plot.html
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://cdn.bokeh.org/bokeh/release/bokeh-1.2.0.min.css" rel="stylesheet" type="text/css">
<script src="https://cdn.bokeh**strong text**.org/bokeh/release/bokeh-1.2.0.min.js"></script>
<title>Stock Plotter</title>
</head>
<body>
<div class=page>
<h1>Stock Plotter</h1>
{{ script|safe }}
{{ div|safe }}
</div>
</body>
</html>
I expect the plot to be visible, but it's not.
No error messages are shown in the console.
Check this post:
Embedding multiple bokeh HTML plots into flask
It has a great example as to how to display bokeh figures in flask apps.
For anyone looking for an answer, the problem with this code is that the plot definition (p.line...) has some problem with my defining the x and y values explicitly. Once I used the source argument, the plot appears as desired.

Proxy to multiple paths angular

I'm trying to proxy to a certain API endpoint that returns an html page but I get the error
Access to font at 'https://data.domain.com/v3/assets/fonts/glyphicons-halflings-regular.woff2' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
GET https://data.domain.com/v3/assets/fonts/glyphicons-halflings-regular.woff2 net::ERR_FAILED
Inside my angular app, I have three different targets that I am proxying to. The first two proxies work fine but the other is a bit weird.
My proxy.conf.json file looks sth like this...
{
"/API": {}, // First proxy works fine
"/info": {}, // Second proxy fine too
"/data": {
"target": "https://data.domain.com/v3/uk",
"secure": false,
"pathRewrite": {
"^/data": ""
},
"changeOrigin": true,
"logLevel": "debug"
}
}
So inside my data service, I define a variable data that contains the path '/data' and I pass that as the path in my POST request like so...
private data = '/data';
public fetchData(data: Data) {
return this.http.post(this.data, data, {responseType: 'text');
}
Upon making that post request, I'm expecting the returned value to be some html code that I'd like to bind to my template. Herein lies the problem. You see, the returned HTML looks something like this...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My Page</title>
<!-- Bootstrap -->
<link href='https://fonts.googleapis.com/css?family=Ubuntu:300' rel='stylesheet' type='text/css'>
<link href="https://data.domain.com/v3/assets/css/bootstrap.min.css" rel="stylesheet">
<link href="https://data.domain.com/v3/assets/css/loading-bar.min.css" rel="stylesheet">
<link href="https://data.domain/v3/assets/css/custom.css" rel="stylesheet">
</head>
<body
<p class="title">Page Title</p>
</body>
</html>
See that bootstrap import? I think that's what's causing the problem because inside the bootstrap.min.css code, references to the glyphicons-halflings-regular font are made like so...
url(../fonts/glyphicons-halflings-regular.woff2) format('woff2'),url(../fonts/glyphicons-halflings-regular.woff) format('woff'),url(../fonts/glyphicons-halflings-regular.ttf) format('truetype')
Hence for each of those font formats, I get the exact same error repeated.
How can I solve this?

Django: Using static, hard time with paths to render css

This is a bit embarrassing, but I don't know how to solve this problem:
First off, my project directory looks like this (there are more directories, but we aren't concerned with them):
projectfolder/
wsgi/
openshift/
templates/
home/
simple-sidebar.html
static/
css/
fonts/
js/
And the file we are concerned with is simple-sidebar.html which looks like the following :
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Starter Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href= "{% static "css/bootstrap.css" %}" rel="stylesheet">
<!-- Add custom CSS here -->
<link href="{% static "css/simple-sidebar.css" %}" rel="stylesheet">
<link href="{% static "font-awesome/css/font-awesome.min.css" %}" rel="stylesheet">
</head>
Now for some reason my static template tags are not working, but that's probably because I don't know how to set up my static template stuff in my settings.py:
STATIC_ROOT = os.path.join(PROJECT_DIR, '..', 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = () <--- dont know if I need this one?
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
PS: Also how would you do this without the {% static %} tag? I am not sure how my style sheets href would look like.
Try removing the dots from your STATIC_ROOT, for example
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
STATICFILES_DIRS are there for you if you'd like to map additional folders to your application that can be anywhere on your machine. When you run ./manage.py collectstatic you're essentially asking python to find all the files within said directories and drop them into the static folder defined in STATIC_ROOT
If you would like to map your files manually (without the static tag) you'd have to write out the full path of your file, for example /some/directory/path/css/style.css.
Lastly if you're running with DEBUG = True you are required to add your static and media urls to urls.py so there is an actual path in place. For example
from django.conf import settings
# ... your normal urlpatterns here
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT}))