static_folder not functioning in Flask debug mode and in development - python

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/...

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.

file gets unresolved warning when trying to extend to html file

I'm trying to use flask-bootstrap in my project and I want to extend my html with bootstrap/base.html , but It can't recognise the file. Here is the Python code (only the part that matters):
from flask import Flask, render_template
from loggin_form import LoggingForm
from flask_bootstrap import Bootstrap
app = Flask(__name__)
app.secret_key = "123string"
Bootstrap(app)
and here is the html:
{% extends "bootstrap/base.html" %}
{% block title %}This is an example page{% endblock %}
{% block navbar %}
<div class="navbar navbar-fixed-top">
something
</div>
{% endblock %}
{% block content %}
<h1>something else</h1>
{% endblock %}
I have tried many things, but not much seems to work. as you can see I have correctly passe the app inside the bootstrap class (it's usually the solution that people with similar problems found) but I already have done it. Also I have correctly installed Flask-Bootstrap and the path directory of bootstrap/base.html is as followed : venv/lib/python3.10/site-packages/flask_bootstrap/templates/bootstrap/base.html
the exact warning that pycharm throws at me: Unresolved template reference '"bootstrap/base.html"'
it does that even if I put the full path directory.
I thank you in advance for your answers guys.
Ps: I am using jinja 2.11.3 and Flask 1.1.4
I found out that the folder inside the venv where the base.html was had to marked as a template folder. Then Pycharm easily recognised it
You need to mark the flask-bootstrap templates folder as a template folder.
In Settings, go to Project Structure and navigate to venv/lib/site-packages/flask_bootstrap. Right-click on the templates folder and mark it as Templates. Apply this and it should work.

Simplest way to assign version numbers to static files in django to avoid caching?

I want to introduce versioning on static files so that the browser doesn't cache them since I will be putting out changes quite often. So currently in my index.html, I call my two files index.css and index.js like so
{% extends "base.html" %} {% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/index.css' %}">
<script type="text/javascript" src="{% static 'js/index.js' %}"></script>
Now I want to introduce versioning such that the browser is forced to fetch the latest files when I update the files with some changes. Offcourse this doesn't mean it should always fetch new files but when I ask it to.
So to do that I need to register a template tag. So I make a folder called templatetags and keep it in the same level where my models.py and urls.py are. (Keeping it elsewhere Django throws error). I name the file as assign_version.py. This is the content inside the file
import time
from django import template
register = template.Library()
#register.simple_tag
def static_version():
print("version changed!!")
version = int(round(time.time() * 1000))
return version
The templatetags folder looks like
assign_version.py assign_version.pyc __init__.py __init__.pyc
Now I change my index.html to refer to these two tags like so
{% extends "base.html" %} {% load staticfiles %} {% load assign_version %}
<link rel="stylesheet" href="{% static 'css/index.css' %}?v={{ static_version }}">
<script type="text/javascript" src="{% static 'js/index.js' %}?v={{ static_version }}"></script>
Then I restart my server. But nothing happens. I do not see the print that I have put to confirm whether this template is being called on restart. Also changing js or css and restarting doesn't seem to force the browser to fetch new files. What am I doing wrong?
First of all please be aware that templatetags are used with {% your_tag %} and not with {{ your_tag }}. So replace {{ static_version }} with {% static_version %} in your template.
However, as the tag is used every time django generates the html page from your template a new "version" is put into your page every time the page is loaded. So you will probably not achieve waht you are intending.
If you want to save the time every time the server is restarted an approach I can think of is using the AppConfig in your apps.py. It is called whan the app is reloaded. So maybe something like this:
In your assing_version.py add the variable "version" as a "global" variable and use this as your version:
#assign_version.py
import time
from django import template
register = template.Library()
version = 0
#register.simple_tag
def static_version():
print("version changed!!")
return version
Set the version in your apps.py
from django.apps import AppConfig
import time
from . templatetags import assign_version
class YourappConfig(AppConfig):
name = 'yourapp'
def ready(self):
assign_version.version = int(round(time.time() * 1000))
For this to work you need to load your app in settings.py with "yourapp.apps.YourappConfig" and not just with "yourapp".
You can use ManifestStaticFilesStorage to achieve this.
From the docs:.
A subclass of the StaticFilesStorage storage backend which stores the file names it handles by appending the MD5 hash of the file’s content to the filename. For example, the file css/styles.css would also be saved as css/styles.55e7cbb9ba48.css.
Reference:
https://docs.djangoproject.com/en/1.10/ref/contrib/staticfiles/#manifeststaticfilesstorage

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%}"

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

Categories

Resources