Problems with Routing, Render and CSS in Flask - python

Problem
I have the css files in /static/ and the html files in /templates/.
When I use simple routing, its works well.
#app.route('/newuser', methods=['GET'])
def newuserform():
return render_template("newuser.html")
But in this code, Flask doesn't render correctly the .CSS files, why?
#app.route('/new/user', methods=['GET'])
def newuserform():
return render_template("newuser.html")
Loading .css files in html,
<!-- Bootstrap core CSS -->
<link href="static/css/bootstrap.min.css" rel="stylesheet">

Set the link as
<link href="../static/css/bootstrap.min.css" rel="stylesheet">
Or better use static urls generator for Jinja2
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='css/bootstrap.min.css') }}">

Related

Blueprints cannot find `static` directory for url_prefixed pages

Been through every question asked here on same topic, but couldn't get my issue resolved. I have a project (modified version of this) directory setted up this way;
I have two links to go to from home page
Admin Dashboard
Dashboard
The admin dashboard page is prefixed by /admin/dashboard whereas the other is /dashboard. I am creating home blueprint (inside home.init.py) by providing the relative path of root static directory;
home = Blueprint('home', __name__, static_url_path='/app/static', static_folder="static")
both the home page and the dashboard page can find the static directory (and load properly), but the admin/dashboard CANNOT fetch static/ resources from admin/static/: GET http://127.0.0.1:5000/admin/static/vendors/bootstrap/dist/js/bootstrap.min.js. the strange thing is, I later added the entire static folder inside admin directory but still it cannot find the above bootstrap.min.js link. Here is my app/init.py file where I am registering the blueprints with app
from .admin import admin as admin_blueprint
app.register_blueprint(admin_blueprint, url_prefix='/admin')
from .home import home as home_blueprint
app.register_blueprint(home_blueprint)
and home/views.py
#home.route('/dashboard')
#login_required
def dashboard():
"""
Render the dashboard template on the /dashboard route
"""
return render_template('home/dashboard.html', title="Dashboard")
#home.route('/admin/dashboard')
#login_required
def admin_dashboard():
prevent non-admins from accessing the page
if not current_user.is_admin:
abort(403)
return render_template('home/admin_dashboard.html', title="Admin Dashboard")
the base.html is listed with some static resources to load.
<link href="{{ url_for('static', filename='vendors/bootstrap/dist/css/bootstrap.min.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='vendors/font-awesome/css/font-awesome.min.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='vendors/themify-icons/css/themify-icons.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='vendors/flag-icon-css/css/flag-icon.min.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='vendors/selectFX/css/cs-skin-elastic.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='vendors/jqvmap/dist/jqvmap.min.css') }}" rel="stylesheet">
According to the docs, providing the static_url_path to prefixed pages should work, do anyone have a clue on what happening wrong here. Any help would be appreciated. Thanks

Configuring output of % static in django

I'm experimenting with django-distill (https://github.com/mgrp/django-distill) to generate a static site from a django project. i'm using django 1.10.8 . My main template contains:
<!-- Bootstrap Core CSS -->
{% load staticfiles %}
<link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet" />
<!-- Custom CSS -->
<link href="{% static "css/landing-page.css" %}" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/jquery.slick/1.5.0/slick.css"/>
The paths to the css and js files are correct when I run the project locally on my windows system. However when I look at the source html I see:
on my windows system this works with a running sever, i.e.
http://127.0.0.1:8000/static/css/bootstrap.min.css
but it breaks with static files and I have to change these to
<link href="./static/css/bootstrap.min.css" rel="stylesheet" />
Is there any way to set % static to render to
./static/ instead of /static/

Django caching CSS (?)

I currently have this template
index.html
<!DOCTYPE html>
{% load staticfiles %} <!-- New line -->
<html>
<head>
<title>GingerBites</title>
<link href='//fonts.googleapis.com/css?family=Lato:400,700' rel='stylesheet' type='text/css'/>
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Dancing+Script" />
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/styles.css"/>
</head>
<body>
</body>
</html>
settings.py
ACTUAL_DIR = os.path.dirname(__file__)
STATIC_PATH = os.path.join(ACTUAL_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
STATIC_PATH,
)
For some reason when running my app locally my css is served correctly, but on page refresh my css remains the same after I save changes and refresh my page. I think something is caching my css. Although when I remove the link to my css, all my css styling disappears. Does anyone know how I can change this?
Or why this might be happening?
Ok, turns out the issue is that static files should be called like so:
{% static /path/to/static %}
So in your case:
<link rel="stylesheet" type="text/css" href="{% static css/styles.css %}"/>
Django documents it here.

Python Pyramid - URL Dispatch and Traversal issue with shash (/)

I have a beginner question with URL Dispatch or Traversal. What I am trying to do, is use Mako renderer to render my views. So I have this folder /includes/ where all the html and css and javascript is. Here is my Pyramid main code:
from pyramid.config import Configurator
def main(global_config, **settings):
config = Configurator(settings=settings)
config.add_static_view('includes', 'includes', cache_max_age=3600)
config.add_renderer(".html", "pyramid.mako_templating.renderer_factory")
config.add_route('home', '/')
config.scan()
return config.make_wsgi_app()
And these are my views:
#view_config(route_name='home', renderer='index.html')
def my_view(request):
return {'name':'Netherdrake'}
#view_config(name = 'login', renderer='login.html')
def login(request):
return {'name':'Netherdrake'}
The problem is, when I access ip:port/login the site works fine, but when I try ip:port/login/ the css, javascript and images don't work. The reason is, my absolute paths become invalid.
And here is my login.html snippet (which is mako template really) while login without /:
<link href="includes/css/twitter/bootstrap.css" rel="stylesheet">
<link href="includes/css/base.css" rel="stylesheet">
<link href="includes/css/twitter/responsive.css" rel="stylesheet">
<link href="includes/css/jquery-ui-1.8.23.custom.css" rel="stylesheet">
<script src="includes/js/plugins/modernizr.custom.32549.js"></script>
And here it is while Im going for login/ path (site is broken in this case, no css, images, js...):
<link href="includes/css/twitter/bootstrap.css" rel="stylesheet">
<link href="includes/css/base.css" rel="stylesheet">
<link href="includes/css/twitter/responsive.css" rel="stylesheet">
<link href="includes/css/jquery-ui-1.8.23.custom.css" rel="stylesheet">
<script src="includes/js/plugins/modernizr.custom.32549.js"></script>
The login.html is in /includes too.
How can I fix this, and make it work under both paths, with and without slash? I tried traveral and url dispatch, and problem is same in both.
All your hrefs should begin with an initial slash.

path resolution in jinja2 templates

I'm using cherrypy with jinja2 templates from a 'views' directory like this:
env = Environment(loader = FileSystemLoader('views'))
When I render the index page:
index = env.get_template('index.html')
it shows up fine, but referenced css, javascripts and images (inside the index.html) are not resolved:
<head>
<link rel="stylesheet" type="text/css" media="screen" href="css/web.css">
<link rel="shortcut icon" type="image/png" href="img/favicon.png">
<script src="js/jquery-1.7.1.min.js" type="text/javascript" charset="utf-8"></script>
</head>
the file system is organized like: views/css , views/js , views/img
What is a robust way to obtain working file resolution?
Static paths in Jinja's templates have nothing to do with Jinja. It's all about the configuration of the web server. If you're using flask, use SharedDataMiddleware dispatcher for static files, i.e.
from werkzeug import SharedDataMiddleware
app.wsgi_app = SharedDataMiddleware(app.wsgi_app,
{ '/static': '/path/to/static/files' } )
The structure of the static directory:
.../static/
img/
css/
js/
etc/
Don't forget to add slash at the beginning of the paths:
<link rel="shortcut icon" type="image/png" href="/static/img/favicon.png">
It is strongly discouraged to use SharedDataMiddleware on production servers. Nginx is the right thing.

Categories