Flask is failing to retreive a random picture from directory [duplicate] - python

How do you use url_for in Flask to reference a file in a folder? For example, I have some static files in the static folder, some of which may be in subfolders such as static/bootstrap.
When I try to serve a file from static/bootstrap, I get an error.
<link rel=stylesheet type=text/css href="{{ url_for('static/bootstrap', filename='bootstrap.min.css') }}">
I can reference files that aren't in subfolders with this, which works.
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='bootstrap.min.css') }}">
What is the correct way to reference static files with url_for? How do I use url_for to generate urls to static files at any level?

You have by default the static endpoint for static files. Also Flask application has the following arguments:
static_url_path: can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder folder.
static_folder: the folder with static files that should be served at static_url_path. Defaults to the 'static' folder in the root path of the application.
It means that the filename argument will take a relative path to your file in static_folder and convert it to a relative path combined with static_url_default:
url_for('static', filename='path/to/file')
will convert the file path from static_folder/path/to/file to the url path static_url_default/path/to/file.
So if you want to get files from the static/bootstrap folder you use this code:
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap/bootstrap.min.css') }}">
Which will be converted to (using default settings):
<link rel="stylesheet" type="text/css" href="static/bootstrap/bootstrap.min.css">
Also look at url_for documentation.

In my case I had special instruction into nginx configuration file:
location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
try_files $uri =404;
}
All clients have received '404' because nginx nothing known about Flask.
The primary configuration file is /etc/nginx/nginx.conf on Linux. It may be similar on Windows.

Related

django css works on chrome but not firefox

I'm developing django website and am using bootstrap, I can see the styles on chrome browser but not firefox.
firefox inspection shows 404 error for the bootstrap and chrome doesn't. Thankful for any idea.
Code :-
#settings.py
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_URL = '/static/'
STATIC_ROOT = '%s/coffestatic/' % (BASE_DIR)
STATICFILES_DIRS = ['%s/website-static-default/'% (BASE_DIR),
("bootstrap", '%s/bootstrap' % (BASE_DIR)),]
HTTP file.html
<head>
{% load static %}
<link href="{% static'bootstrap/css/bootstrap.css'%}"rel="stylesheet">
</head>
Files structure
BASEDIR
|--ProjectFolder
|------Apps
|--BootstrapDir
|------css
Work flow
Define static files
python manage.py collectstatic
Define styles in html
run project
Thanks
I'm not sure if your settings.py files are correct as they are different from how I would set things up. That being said, I'm no expert and you may well be running a different version of django to me. What I did notice though is you don't have a file type on your link file. Maybe Chrome is fine without this but maybe Firefox is having a hissy fit without it. Try changing:
<link href="{% static'bootstrap/css/bootstrap.css'%}"rel="stylesheet">
to
<link href="{% static'bootstrap/css/bootstrap.css'%}"rel="stylesheet" type="text/css">
Just a guess....
Using bootstrap starter file in your html file will help; as I have done the same and it helped.
Add these files at the end in body section:
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRS
and add these files at the starting in head section:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
I'm a beginner at django so not sure about it but it worked for me.
In project folder create a directory with any name. Let's name __shared__ and put the css and jss folders inside the directory
and in settings.py
at bottom put this code
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "__shared__"),
]

Link to style.css not working

I am pretty new to web programming and Flask. I'm trying to link a .css file to the head of my base.html file. I can render the content of the website but not the styles from the .css file. This is my directory:
app
templates
base.html
index.html
views.py
static
style.css
In the head of base.html i wrote:
<head>
...
<link rel="stylesheet" type="text/css" href="/static/style.css">
</head>
I also tried this one:
<head>
...
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
</head>
And also some variations copying the .css file around my directory. Still no formatting on the website.
Some further information: By running the views.py I render the index.html which extends the base.html - I don't know if this might be relevant.
Please try this . It may help
in .py file
from flask import Flask, request, send_from_directory
# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='')
#app.route('/static/<path:path>')
def send_css(path):
return send_from_directory('static', path)
in .html file
**
<head>
...
<link rel="stylesheet" type="text/css" href="../../../static/style.css">
</head>
**
edit :
<head>
...
<link rel="stylesheet" type="text/css" href="../../../static/style.css">
</head>
I got it! My directory division was wrong. I put the static folder outside of the app folder - I do not know why but Python could not link outside of the app folder. Thank you for your help, everyone!
please try this and please give path to static_folder correct means it must point to the 'static' directory.
import os
from flask import Flask, request, send_from_directory
app = Flask(__name__, static_folder = 'path/to/folder/of/staticfiles')
#in your case it is 'static' directory.
#app.route('/static/<path:path>/<filename>')
#app.route('/static/<filename>')
def send_css(**kwargs):
filename = kwargs.get('filename')
path = kwargs.get('path')
if path:
return send_from_directory(os.path.join(static_folder,path), filename)
else:
return send_from_directory(static_folder, filename)
This will also read .css files from any subdirectory of your 'static' directory.
just keep this in your index.html.
<head>
...
<link rel="stylesheet" type="text/css" href="/static/style.css">
</head>
I hope your are Extending base.html in index.html
and rendering index.html from flask.
And Did you understand what path you have to give in your static_folder in app = Flask(__name__, static_folder = 'path/to/folder/of/staticfiles') ????
You have to add path of your directory where .css file is kept means your's path of 'static' folder.

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

use a css stylesheet on a jinja2 template

I am making a website using html, css, flask and jinja2.
I have a page working on a flask server, the buttons and labels etc. are displayed, but the css stylesheet I have is not loaded in.
How would I link a stylesheet to a jinja2 template. I have looked around on the internet but cannot find out how.
Here is the css stylesheet link; should I change this, or the python code?
<link rel="stylesheet" type="text/css" href="styles.css">
here is my flask code:
#app.route('/')
def resultstemplate():
return render_template('questions.html', head='Welcome!')
here are the locations of the files:
/python-code.py
/templates/template.html
/templates/styles.css
All public files (the ones that are not processed, like templates or python files) should be placed into dedicated static folders. By default, Jinja2 has one static folder called static.
This should fix your problem:
Move /templates/styles.css to /static/styles.css
Update your code with following code, that will be translated into correct file location:
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
More info on static files in Jinja2 is here.
<link rel="stylesheet" type="text/css" href="styles.css">
href value must be within quotes.
make sure the file name and path are proper
OR try the below
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}"/>
The order of handler might cause the problems:
url: /stylesheets static_dir: stylesheets
url: /.* script: helloworld.application
will work instead of
url: /.* script: helloworld.application
url: /stylesheets static_dir: stylesheets
you should use the super() block style .
see the code below:
{% block style %}
{{ super() }}
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}"/>
{% endblock %}
Tried almost every solution on Stack Overflow. It only worked for me when I placed the static folder in the same directory as my run.py file.
I changed my folder structure from:
app/
views
static
templates
run.py
To:
app/
views
templates
static
run.py
I guess moving the run.py instead would work too. Have a look at this Jinja Templating Tutorial for extra info. Not sure why I had to change the structure for it to work though.
To add to what's been said here, be sure to update Jinja2 to v2.10, as lesser versions seem to cause this same bug. Cheers!

Django STATIC_FILE doesn't work as i thought?

I've searched for answer for this question, but i havent found any solution for my problem. I want to link css to my project, but just cant handle how STATIC_URL work
<head>
{% load static from staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">
</head>
it's to much code to post here so here are the links:
settings.py: http://pastebin.com/9Bsg3u1h
And I render with context_instance=RequestContext(request) parameter of course.
I got files structure like this:
Django_project
...
appname
templates
static
I tried also to place static directory in many project, in appname, and even in templates.
Can someone explain me how should it look for my project?
Use the builtin static, not static from staticfiles:
<head>
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">
</head>
 
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#static
Django ships with a static template tag. You can use this regardless if you’re using RequestContext or not.
Note
The staticfiles contrib app also ships with a static template tag which uses staticfiles' STATICFILES_STORAGE to build the URL of the given path. Use that instead if you have an advanced use case such as using a cloud service to serve static files...

Categories

Resources