I'm working on a Django project (Django 1.11), and I'm trying to use static file.
This is my project structure:
|project_name
|---- app_name
|-------- src
|------------ static
|---------------- css
|-------------------- bootstrap
|------------------------ bootstrap.min.css
|-------- templates
|------------ base.html
|------------ first_template.html
|-------- views
|------------ first_view.py
|---- project_name
|-------- settings.py
In settings.py file, I have django.contrib.staticfiles in INSTALLED_APPS and I set STATIC_URL variable as follow:
STATIC_URL = '/src/static/'
Then, I'd like use static files in base template, and this is what I've done:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}</title>
<link href="{% static "css/bootstrap/bootstrap.min.css" %}" rel="stylesheet">
</head>
<body>
{% block content %}{% endblock content %}
</body>
</html>
When I load first_template.html, and so also the base.html file, the bootstrap.min.css file is not found (404).
I know that is a trivial question, but i really don't understand what i'm missing. I have checked a lot of similar SO questions without success, also because most of them refer to old django versions
Thank you in advance
Since you are using customised path, why dont you tell the django where to find it.. use this in settings and it shall work fine.
option 1:
in case you are serious about preserving your file structure
#settings.py
STATICFILES_DIRS = (
...
os.path.join(BASE_DIR, 'app/src/static') # build appropriate path
)
UPDATE:
option 2:
move the static folder to where manage.py exists or into the child of app.
example:
...manage.py
...static
...app/
or
...manage.py
...app/static
STATIC_URL only control the prefix of static files URL (i.e web address). It doesn't control their physical location on disk.
Move your static files from app_name/src/static/ to app_name/static/ and that should fix it
Edit:
If you want to keep directory structure as it is, you have couple of options
Manually add your static file directories to STATICFILES_DIRS
Create a class that inherit from django.contrib.staticfiles.finders.AppDirectoriesFinder and set the source_dir attribute
from django.contrib.staticfiles.finders import AppDirectoriesFinder
class MyAppDirFinder(AppDirectoriesFinder):
source_dir = "src/static"
Then you can add your class to STATICFILES_FINDERS
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'myapp.finders.MyAppDirFinder',
]
Reference: https://docs.djangoproject.com/en/1.11/ref/settings/#static-files
Indside static folder you need to create a folder with app name
Now your folder structure is
|-------- src
|------------ static
|---------------- css
|-------------------- bootstrap
|------------------------ bootstrap.min.css
Change it to
|-------- src
|------------ static
|-------------------app_name
|--------------------------- css
|-------------------- ----------bootstrap
|---------------------------------------- bootstrap.min.css
add
STATICFILES_DIRS=(os.path.join(BASE_DIR, '../frontend'),)
or
STATICFILES_DIRS=()
in your settings.
Then it should work.
Took me a long time to find this.
Related
The current project I've started working on, uses django 2.2 and most of the links are hardcoded.
All static content is in folder named media and used in base.html as follows
in base.html
{% load staticfiles %} ---- using this as first line of base.html
.......
.......
<head>
<link href="/media/css/backoffice/font-awesome.min.css" rel="stylesheet" type="text/css">
</head>
in settings.py
STATIC_URL = '/media/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'media'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'media/')
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
I've also added following to the main urls.py file:
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Yet I'm not able to render the static file listed in the head section of base.html
I've also experimented with commenting out static root and staticfiles_dir but it does not work
You need to put all files in project root's static folder and run this command:
python manage.py collectstatic
For loading static files in the template you need to write this:
{% load static %}
And in all the static files like css, js and images you can do like this:
{% static "<absolute path of file>" %}
And you can refer from documentation.
I hope this will help you!
I tried fetching static files for my website but nothing seems to work even the other stackoverflow answers.
please help on this.
settings.py -
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static','static_root')
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static','static_dirs')
]
File is present in :
parent_folder>static>static_dirs>css>cover.css
HTML
<html lang="en">
{% load staticfiles %}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="Aman Turate">
<title>Aman Turate - Resume</title>
<link rel="stylesheet" href="{% static 'css/cover.css' %}">
This works for me. Update your settings.py to this
.........
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
.........
Make sure the static folder is in the root (i.e where manage.py is)
There are several things to consider here and I am not sure which applies because I'm working on pure assumptions of your situation without knowing:
What is BASE_DIR set to
Have you run manage.py collectstatic
what is your server setup or are you just working off the django development server?
Where are the files you're trying to link to actually placed
Anyway here is some info I hope will be useful. I will break down how the settings files relates to your template file and hopefully that will help you debug your problem.
STATIC_URL = '/static/' -- > the value of this is what will be appended to the static file you are linking in your template. It is the relative url after your domain name. So {% static 'css/styles.css' %} will be rendered as /static/css/styles.css in your html page when it is loaded.
STATIC_ROOT is the absolute path of where your files are located on disk. It tells django where to place all static files collected from your apps when you run manage.py collectstatic see here for details.
STATICFILES_DIRS tells django where to find project static files. By default Django will look for a static directory in each registered app and collect the files in there and place then in your STATIC_ROOT folder. If you want to put static files in a different directory in your project and you want django to know about it then you list those paths in this config variable.
With your code:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static','static_root')
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static','static_dirs')
]
{% static 'css/cover.css' %} is translating to /static/css/cover.css, your telling django the root directory to collect static files is <your BASE_DIR>/static/static_root so here you can see that there might be a miss match in locations. Again I don't know if you ran collectstatic. your STATICFILES_DIR is just going to look for static files in <your BASE_DIR>/static/static_root to then put them in <your BASE_DIR>/static/static_root ... if that makes sense.
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%}"
I've designed a single page,including an 'index.html' and some css and 'js' files in separate folders. Then i decided to take my web page to django so that i can add database and a little management system to some contents in my web page. But I can't work it out. this is how I tried it so far.
url.py
urlpatterns = patterns('',
# Examples:
url(r'^$', 'mysite.views.home', name='home'),
)
views.py
def home(request):
return render_to_response('index.html')
setting.py
TEMPLATE_DIRS = ('/var/www/html/mysite/templates',)
I've put my index.html files and it's relatives folders into templates folder. But when i run the server it shows my homepage without recognizing my css and 'js' files.
I'm wondering what's the right way to do that.
Thanks for your help.
--Update 1--
So referring to this document I've set my static file stuffs like this
I've Created 'static' folder in my project ND Added one more line in 'setting.py'
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(PROJECT_PATH, 'static')
STATIC_URL = '/static/'
Then I transferred all my 'css' and 'js' files to that folder.
I added this two lines to my home page to check if it works
{% load staticfiles %}
<img src="{% static "/img/b-img-4.jpg" %}" alt="My image"/>
Also I tried this command
python manage.py collectstatic
This is the error line for the new '' tag I added.
[24/Dec/2014 19:27:29] "GET /img/b-img-4.jpg HTTP/1.1" 404 2163
--Update 2--
I found out my mistake. I changed my <img> tag like this
<img src="{% static "admin/img/b-img-4.jpg" %}" alt="My image"/>
But problem is that it just recognizes its default static files and folders. I add my own file and folders and ran python manage.py collectstatic But It doesn't show the new files I add.
This is my folders srtructure
mysite--
|
mysite
| |
| static
| |
| my css js files
|
templates
|
index.html
What am I doing wrong?
You are nearly there, but you shouldn't be putting the other resources (JS, CSS, images) into the templates folder. That's only for templates! You need to read the static files docs:
https://docs.djangoproject.com/en/1.7/howto/static-files/
This is needed to ensure proper separation of your code (which includes templates - they are a kind of server-side code) and your resources.
(If you come from a PHP background, you might be frustrated by this, because it seems more complicated than PHP where you can just mix them together. However, the way that PHP mixes these things is a really bad idea that leads to multiple security vulnerabilities).
Your static folder is not where it's supposed to be. Try this:
mysite
static
js
css
images
b-img-4.jpg
If your image is placed as shown in the above tree, this should work:
<img src="{% static "images/b-img-4.jpg" %}" alt="My image"/>
So This blog made it all Crystal clear and with these settings I could make it works
setting.py
STATIC_URL = '/static/'
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(PROJECT_PATH, 'static')
STATICFILES_DIRS = (
os.path.join(PROJECT_PATH, 'static_assets'),
)
index.html
{% load static from staticfiles %}
<img src="{% static 'img/author.jpg' %}" alt="My image"/>
Folder Structure
mysite--
|
mysite
| |
| static
| |
| my css js files
|
static_assets
|
templates
|
index.html
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