Serve static files located under Flask blueprint folder - python

I have a Flask blueprint that contains templates and static files. The template is rendered correctly but the linked CSS file returns 404 not found. How do I serve static files that are located under a blueprint's folder?
app/
__init__.py
auth/
__init__.py
static/
style.css
templates/
index.html
auth = Blueprint('auth', __name__, template_folder='templates')
#auth.route('/')
def index():
return render_template('index.html')
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">

Tell the blueprint where its static folder is by passing static_folder, then use url_for to generate urls to the static route on the blueprint. This is described in the docs.
auth = Blueprint('auth', __name__, template_folder='templates', static_folder='static')
url_for('auth.static', filename='style.css')
This solution only works if the blueprint has a url_prefix. As per the docs:
However, if the blueprint does not have a url_prefix, it is not possible to access the blueprint’s static folder. This is because the URL would be /static in this case, and the application’s /static route takes precedence. Unlike template folders, blueprint static folders are not searched if the file does not exist in the application static folder.
In this case, one solution might be to put the stylesheet into the main static directory.

Related

Python Flask: How to include JavaScript file for each template per blueprint

I have read Loading external script with jinja2 template directive and Import javascript files with jinja from static folder but unfortunately no closer
I have a Python Flask site which is based on https://hackersandslackers.com/flask-blueprints/ so each blueprint has its own static and templates folder
My question is how would I include a JS file within a block that sits within a static/js folder of the blueprint?
My suggestion is to set a separate static_url_path for each blueprint unless a url_prefix is defined. This adds a prefix to the URL where the static files will be loaded.
bp = Blueprint(
'home', __name__,
template_folder='templates',
static_folder='static',
static_url_path = '/home/static'
)
# ...
bp = Blueprint(
'products', __name__,
template_folder='templates',
static_folder='static',
url_prefix = '/products',
)
# ...
With the help of the request object, the name of the current blueprint can be determined. This can then be used to load the static file. Thus, a different file is loaded for each blueprint.
{% block javascript %}
<script src="{{ url_for(request.blueprint+'.static', filename='js/main.js') }}"></script>
{% endblock %}
It is therefore necessary to adapt both the template_url_path or url_prefix and the identifier within url_for to the requirements.

Django - Display an image with static files

I have some issues with "static files" in my project
I'd like to simply load an image.
Here is my code :
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
# Create your views here.
def D3(request):
     template = loader.get_template('appli1/D3.html')
     context = {}
     return HttpResponse(template.render(context, request))
urls.py
from django.conf.urls import url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
 
from . import views
 
urlpatterns = [
    url(r'^D3$', views.D3, name='D3'),
]
D3.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
    {% load staticfiles %}
    <img src="{% static "appli1/testimg.png" %}" alt="My image"/>
</body>
</html>
settings.py
STATIC_URL = '/static/'
The image testimg.png is in appli1/static/appli1/
And the file D3.html is in appli1/templates/appli1/
Thanks for your help !
EDIT :
The structure of my project seems good to me, maybe I'm wrong. Here is what it looks like :
test_django/
manage.py
db.sqlite3
test_django/
__init__.py
settings.py
urls.py
wsgi.py
__pycache__/
...
appli1/
__init__.py
admin.py
apps.py
models.py
tests.py
urls.py
views.py
__pycache__/
...
migrations/
...
static/
appli1/
testimg.png
templates/
appli1/
D3.html
There are following issue with your code:
1) Check quotes in
<img src="{% static "appli1/testimg.png" %}" alt="My image"/>
Technically,in the above "{% static " will be read as one value, then " %}" as other, and finally "My image" as another.
Following is the correct way of doing it:
<img src="{% static 'appli1/testimg.png' %}" alt="My image"/>
This way html read it "{% static 'appli1/testimg.png' %}" as a whole inside which lies 'appli1/testimg.png'.
2) As I don't know your directory structure and hence your root directory, this might be another issue.
If in your 'appli1/static/appli1' your 'static' is at the same level as that of root directory, then it will work fine, which I think is the case as even your templates are in 'appli1/templates/appli1/' and your templates are being loaded. Hence proving that 'static' is at the root level.
Else, if its not the case, and even your templates are not loaded (Coz i'm just assuming your templates are being loaded), then your root 'static' and 'templates' folder are not the same level of root directory and hence the html and static files are not being discovered by the url you are specifying in your html.
One of the issues you might be having is that your STATIC_DIR setting in your project's settings.py file might not be configured. The Django docs have a section on that which is really easy to follow along. After you do that, when you have the {% load static %} tag, when you insert a {% static 'path/to/file.txt' %} tag, Django will look in your projects main static file and then find the app folder and then follow the path you lay out from there. for example, if your file is in an app called 'main' in static/main/images/fart.png, then all you have to do is put scr="{% static static/main/images/fart.png%}"

Flask Templates couldn't load css

I followed this tutorial for develop templates with flask http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ii-templates
My file tree is the next one:
/static
/js
bootstrap.min.js
jquery_1.11.3.js
/css
bootstrap.min.css
/images
/templates
index.html
/python_venv
server.py
server.py code:
#app.route('/subdomain/')
def getPrevisionPoblacion():
return render_template('index.html')
And css link inside index.html code is the following:
<script src="/static/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="/static/css/bootstrap.min.css"/>
<script src="/static/js/jquery_1.11.3.js"></script>
nginx config:
location /subdomain/{
root /apps/subdomain/static;
uwsgi_pass unix:///tmp/subdomain.sock;
include uwsgi_params;
}
When I check it on Chrome, the index didn't load the CSS files. I checked the network with Developer's tools and the error is 404.
I tried also similar code that i saw on this unresolved question without success
Inline CSS background:url() not working in Jinja2 template
Any help about this ?
The problem was the server.
I had to serve static folder for flask template can load css.
I wrote in nginx config file the next:
location /subdomain/static)/ {
root /opt/apps/content_folder/static;
}
I don't use url_for() function y wrote the resource's URL as:
static/css/my_css_template.css
Finally check out #app.route() inside the file that render the template was correct then flask template could access to css, images and js.
if you put the static files directly under the /static folder, this should work
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='bootstrap.min.css') }}">
if you do not want that, follow the instructions in this questions approved answer,
Link to Flask static files with url_for

django not found static files in the subfolder of static

django 1.6.5
My static files is under subfolder of static.
djangoprj
djangoprj
settings.py
urls.py
wsgi.py
__init__.py
static
myapp
mystaticfiles
...
apps
myapp
...
templates
*.html
...
In my templates file, I link static file as full path.
<img src="/static/myapp/images/my.png" />
But those file are not found. I got 404 error.
When change settings.py as
STATIC='/static/myapp/'
I can get those static files. But I am not want to do that. Why dose it not wok, when STATIC='/static/'? Is there some easy way to solve this problem instead of doing command manaully, such as 'collectstatic'? I have put my static file in static folder, and I have used full path in my templates file. Why does it not work? Thanks in advance.
Now that you switch the static file folder to '/static/myapp/'
You should use <img src="/static/images/my.png" /> in your tag.
Generally, you should use {% static %} template tag to do this, like below (assume STATIC='/static/').
{% load staticfiles %}
<img src="{% static 'myapp/images/my.png' %}" />
to learn more, see the tutorial, https://docs.djangoproject.com/en/1.6/intro/tutorial06/
I suggest you to read all the tutorial (part1 - part6) in https://docs.djangoproject.com/en/1.6/
So that you can know deep enough for the basis.
You can found some help in these answers also
static files problem
STATIC_URL Not Working
In my configuration I have a directory structure where static files are inside my app like this
djangoprj
djangoprj
settings.py
urls.py
wsgi.py
__init__.py
apps
myapp
...
templates
*.html
static
myapp
mystaticfiles
...
...
In settings
INSTALLED_APPS = (
...
'django.contrib.staticfiles',
...
)
STATIC_URL = '/static/'
and in templates I use 'static' tags
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'posts/style.css' %}" />
I hope this can help you

static_folder not functioning in Flask debug mode and in development

My file structure:
my_app
/models
/views
/templates
/other_folders
/www (where flask resides)
/templates
some_files.html
/static
/css
style.css
/views
/models
my_app.py (run the app in console)
web_my_app.py (run flask app)
In web_my_app.py, here's how my static_folder is set:
app = Flask('my_app',
template_folder='www/templates/',
static_folder='www/static'
)
# As a test, let's develop a basic page
#app.route('/')
def show_index():
return render_template('main.html', entry="hello")
The main.html look like this:
{# Main page #}
{% extends "layout.html" %}
{% block body %}
<h2>Main Page</h2>
{{ entry }}
{% endblock %}
The layout.html has the following for stylesheet
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='css/style.css') }}">
Question: Why do I get a 404 on my static page but not on my template?
The app manages to access the template files just fine and dandy but has no clue where the static pages are.
I think you will find that the static files are fine and accessible at http://localhost:5000/www/static/....
Flask's development server by default makes static files available with the same URL prefix that you provide in the static_folder argument. If you want the URL to be different you have to add the static_url_path argument to your Flask constructor. Example:
app = Flask('my_app',
template_folder='www/templates/',
static_folder='www/static',
static_url_path='/static'
)
And now you can find your static files at http://localhost:5000/static/...

Categories

Resources