Blueprints cannot find `static` directory for url_prefixed pages - python

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

Related

i can not show the images in html

I´m new in python and django.
My code is below and the problem is that the images do not appear.
I include in the teste.html this tag but it didn´t work src="./assets/images/3ed274bc061c771ef0b153111a6fe932_logocartorio.png"
My path is:
BCcartorio
bccartorio
settings
urls
iddigital
views
urls
templates
iddigital
teste.html
assets
css
images
js
My iddigital.views.py:
from django.shortcuts import render, HttpResponse
def home(request):
return (render(request, "iddigital/teste.html"))
My teste.html:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>teste</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</head>
<body>
<h1>Welcome</h1>
<button class="btn btn-danger" type="button" name="button">login</button>
<div class="bd-vertical-align-wrapper">
<img class="bd-imagelink-1 bd-own-margins bd-imagestyles " src="./assets/images/3ed274bc061c771ef0b153111a6fe932_logocartorio.png">
</div>
</body>
</html>
It is not a good practice to hard-code the URL of an image as this can cause many unexpected problems(e.g. paths mixup). In order to avoid this Django provides a hassle-free way to manage and serve your static files easily.
First you have to include the django.contrib.staticfiles app in your INSTALLED_APPS and then define in your settings file the STATIC_URL which will serve as the base path that'll be used by Django to find your static files in a template. It is a good practice to have a separate static folder that will contain the assets folder which -in turn- will contain your css, js, images etc sub-folders.
So I'd take the assets folder from that path and put move it in a static folder that would be in the same level as the iddigital and templates ones. In that case your STATIC_URL variable would be equal to '/static/.
Now in the teste.html template you can load your static folder by adding {% load static %} at the top of your file. Your images can now be called as simple as this: <img src="{% static "assets/images/logocartorio.png" %}" class="bd-imagelink-1 bd-own-margins bd-imagestyles"/>
More info on the above can be found at the excellent Djangodocumentation.

How to keep relative path in Django templates?

I have imported a front-end project including completed .css, .js, .html files into Django templates. They can work when run .html directly. But if run them in Django server, all links with relative path should be modified as Django style such as
<link rel="stylesheet" type="text/css" href="{% static 'style.css' %}" />
instead of
<link rel="stylesheet" type="text/css" href="css/style.css" />.
Is there any method to keep the orginal relative path in .html file and also can run in Django?
===========================================================================
I've solve my problem, the solutions are add their path into urls.py under primary program.
if settings.DEBUG:
urlpatterns += [
url(r'^(?P<path>css.*)$', views.serve),
url(r'^(?P<path>images.*)$', views.serve),
url(r'^(?P<path>js.*)$', views.serve)]

Adding documentation to django app - conflict with angular

I have created documentation for my Django app using apidoc library.
It creates docs using angular. App is running on Heroku.
Docs are working nicely when I open index.html file, but I cannot open them via http://localhost:5000/docs.
Firstly I got this error:
"Variables and attributes may not begin with underscores: '__' "
, which I was able to bypass by putting {% verbatim %} and {% endverbatim %} into the index.html file. (Which I'm not very happy with in the first place and would like to do it some other way).
Then the page is stuck on the loading screen, but when I open it in Chrome I have the following error:
"Uncaught SyntaxError: Unexpected token <" in polyfill.js:1 and
require.min.js:1
And also 3 warnings:
"Resource interpreted as Stylesheet but transferred with MIME type
text/html"
in vendor/bootstrap.min.cs, vendor/prettify.css and css/style.css
We are using apidocs also in other project with Node where it works perfectly, so I think it's an issue with Django. Since the documentation is generated automatically, I would prefer to introduce changes into the app, not docs.
I tried it on Chrome and Safari.
My questions
1. What can I do to make it work?
2. How can I make Django compatible with Angular without putting {%verbatim%} tags into index.html?
Here is my controller:
from django.shortcuts import render
def show_docs(request):
return render(request, 'index.html')
and url_pattern:
from django.conf.urls import include, url
from django.contrib import admin
admin.autodiscover()
import my_app.controller
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
url(r'^docs/', my_app.controller.show_docs),
]
index.html head:
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Loading...</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="vendor/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="vendor/prettify.css" rel="stylesheet" media="screen">
<link href="css/style.css" rel="stylesheet" media="screen, print">
<link href="img/favicon.ico" rel="icon" type="image/x-icon">
<link href="css/apidoccustom.css" rel="stylesheet" media="screen, print">
<script src="vendor/polyfill.js"></script>
</head>
edit:
Thanks to answer from hubert, I was able to find the source of the problem.
It turns out, that Django doesn't work that good with RequireJS, which is used by api docs.
I had to add the following changes to the generated code to make it work:
Points 1-4 are for index.html, point 5, 6 are for main.js:
Add this line above tag:
{% load static %}
Add "{% static" + " %}" tags to all tags so it looks like this:
<link href="{% static "vendor/bootstrap.min.css" %}" rel="stylesheet" media="screen">
Add the same static tags to tags with polyfill.js and require.min.js:
<script src="{% static "vendor/polyfill.js" %}"></script>
<script data-main="{% static "main.js" %}" src="{% static "vendor/require.min.js" %}"></script>
Add {% verbatim %} at the beginning of and {% endverbatim %} at the end of , BUT BEFORE with require.min.js!
In main.js add following lines to paths at the beginning of the file:
apiProject: './api_project.js',
apiData: './api_data.js',
Change lines:
'./api_project.js',
'./api_data.js',
to:
'api_project',
'api_data',
From this two errors:
"Uncaught SyntaxError: Unexpected token <" in polyfill.js:1 and require.min.js:1
"Resource interpreted as Stylesheet but transferred with MIME type text/html"
I would assume that there is something wrong with loading your static files. Probably you have 404 or 500 on them and django loads then default route.
Check if you have correct routing for static files.

Problems with Routing, Render and CSS in Flask

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') }}">

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.

Categories