42π
If you follow djangoβs guidelines, you can simplify your life greatly.
In your sample code, inside your application directory, create a folder called static. Inside this folder, place your css files.
Example:
$ django-admin.py startproject myproject
$ cd myproject
myproject$ python manage.py startapp myapp
myproject$ mkdir myapp/static
myproject$ cd myapp/static
myproject/myapp/static$ nano style.css
In your templates:
<link rel="stylesheet" href="{{ STATIC_URL }}style.css" />
Make sure you add myapp
to the INSTALLED_APPS
list in settings.py
. Now when you use the built-in development server, your style sheet will be rendered correctly.
Django searches for a static
directory inside installed applications by default, and with current versions of django, static files are enabled by default.
The Django example has the path
my_app/static/my_app/myimage.jpg
which
is a little confusing if your app and project have the same name.
This is recommended because when you run collectstatic
to gather all your static files, files with the same name will be overwritten. If you have a file called myimage.jpg
in another application, it will be overwritten. Giving the application name inside the static directory will prevent this, because the exact directory structure will be replicated inside your STATIC_ROOT
directory.
A simple example to illustrate the point. If you have a django project with two apps, like this:
.
βββ assets
βββ manage.py
βββ myapp
βΒ Β βββ __init__.py
βΒ Β βββ models.py
βΒ Β βββ static
βΒ Β βΒ Β βββ myapp
βΒ Β βΒ Β βββ test.txt
βΒ Β βββ tests.py
βΒ Β βββ views.py
βββ myproj
βΒ Β βββ __init__.py
βΒ Β βββ __init__.pyc
βΒ Β βββ settings.py
βΒ Β βββ settings.pyc
βΒ Β βββ urls.py
βΒ Β βββ wsgi.py
βββ otherapp
βββ __init__.py
βββ models.py
βββ static
βΒ Β βββ otherapp
βΒ Β βββ test.txt
βββ tests.py
βββ views.py
assets
is your STATIC_ROOT
. Now when you run collectstatic
:
.
βββ assets
βΒ Β βββ myapp
βΒ Β βΒ Β βββ test.txt
βΒ Β βββ otherapp
βΒ Β βββ test.txt
βββ manage.py
βββ myapp
βΒ Β βββ __init__.py
βΒ Β βββ __init__.pyc
βΒ Β βββ models.py
βΒ Β βββ static
βΒ Β βΒ Β βββ myapp
βΒ Β βΒ Β βββ test.txt
βΒ Β βββ tests.py
βΒ Β βββ views.py
βββ myproj
βΒ Β βββ __init__.py
βΒ Β βββ __init__.pyc
βΒ Β βββ settings.py
βΒ Β βββ settings.pyc
βΒ Β βββ urls.py
βΒ Β βββ wsgi.py
βββ otherapp
βββ __init__.py
βββ __init__.pyc
βββ models.py
βββ static
βΒ Β βββ otherapp
βΒ Β βββ test.txt
βββ tests.py
βββ views.py
You see it is creating the directories as well. In your templates you would now refer to each file with its βnamespaceβ of the app: {{ STATIC_URL }}/myapp/test.txt
14π
The recommended approach has changed again (from at least Django 1.5 I think).
At the top of your template put:
{% load staticfiles %}
Then, using the same directory structure (myapp/static/myapp/style.css
):
<link rel="stylesheet" href="{% static 'myapp/style.css' %}" />
- [Django]-Django "get() got an unexpected keyword argument 'pk'" error
- [Django]-Django: how do I query based on GenericForeignKey's fields?
- [Django]-Django or Ruby-On-Rails?
7π
For the examples you pointed at to work, your static files need to be in a location accessible to Djangoβs built-in staticfiles
app.
There are a couple steps to make this happen:
First, within your project directory (ie beside your manage.py
file), youβll need to create a directory to hold your static files. Call it βstatic_filesβ.
Next, youβll need to let Django know to look in that directory, by specifying it in the list of STATICFILES_DIRS
within your settings.py
file.
Something like this:
STATICFILES_DIRS = [
'/full/path/to/your/project/static_files/',
]
Within that static_files
directory, you can create whatever structure you want, so that is where your css
and js
directories could go.
After that, you should be able to use the {{ STATIC_URL }}
tag in your templates to get access to the base URL of your static files.
So, say, for example, you create project/static_files/css/base.css
, you would use it in your template like so:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}/css/base.css" />
Hope that helps!
Edit
With the default settings for STATICFILES_FINDERS
, Django should automatically serve up any files from directories listed in your STATICFILES_DIRS β see the docs for details.
If this doesnβt work, some things to check:
- Have you edited your
STATICFILES_FINDERS
setting to something other than the default? - Is
django.contrib.staticfiles
in your list ofINSTALLED_APPS
insettings.py
? - Are you using Djangoβs built-in server (
python manage.py runserver
)? - Do you have
DEBUG = True
in yoursettings.py
? If not, youβll need to either set it toTrue
or use theinsecure
option (python manage.py runserver --insecure
). When going to production, check out thecollectstatic
command.
- [Django]-When I run test cases I get this error: psycopg2.OperationalError: cursor "_django_curs_140351416325888_23" does not exist
- [Django]-Django accessing ManyToMany fields from post_save signal
- [Django]-Make clicked tab active in Bootstrap
4π
finally i got after many days here is how should be done
1> you need your static file in your app along with in your project
2> here is setting.py
if DEBUG:
STATIC_ROOT = "/PycharmProjects/don/admin/shopping/static/css"
STATICFILES_DIRS =(
#os.path.join(os.path.dirname(BASE_DIR),"static","static"),
os.path.join(BASE_DIR, "static"),
)
3>views.py
from django.views.generic import TemplateView
class HomeView(TemplateView):
template_name = 'index.html'
4> template file
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
5> urls.py
from shopping.views import HomeView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', HomeView.as_view())
]
if settings.DEBUG:
urlpatterns+=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
6> python manage.py collectstatic
have fun :)
- [Django]-Django 1.7 upgrade error: AppRegistryNotReady: Apps aren't loaded yet
- [Django]-Inline in ModelForm
- [Django]-Django: How to rollback (@transaction.atomic) without raising exception?
3π
The handling of static files has changed significantly (for the better) in Django 1.3. In particular is the flexible difference between static files (think code required CSS/JS/images) and media files (think images uploaded by users in the use of you application). The staticfiles
app handles what you are asking for.
Put django.contrib.staticfiles
in your settings.py INSTALLED_APPS. Then create a static
directory inside your app directory β so project/app/static/
. Within that static directory organize your support files as you like (css/, js/, images/, icons/, etc). staticfiles
by default will look in the static/ directory for every app listed in INSTALLED_APPS. Not just your own, but all the Django apps and third-party apps. (sidenote: the Admin in Django 1.4 moves to this paradigm while in 1.3 it still uses the ADMIN_MEDIA_PREFIX).
The staticfiles
app knows about all those static/ directories in all the apps but it needs to collect all that content in order to serve it. In development, when using manage.py runserver
it is handled for you. Django will run your site and automatically deliver all the static content from all the static sources. (Sources, as mentioned in another answer, are set in the STATICFILES_FINDERS setting.) When not using runserver, use manage.py collectstatic
to gather all the static files into the folder defined in STATIC_ROOT
. Keep this directory empty. It is a collection destination. Of course your web server will need to be configured to serve this directory.
Now there is one more piece β the view. This is where the STATIC_URL
comes into play. When referring to static files in your templates, the easiest way is to use {{ STATIC_URL }}
. Django by default makes that variable available to any view using the RequestContext. Do something like this β <link rel="stylesheet" href="{{ STATIC_URL }}/css/main.css" />
.
For more information and more ways to refer to STATIC_URL in your templates, check out this answer to a similar question.
- [Django]-How to upload multiple files in django rest framework
- [Django]-How to pull a random record using Django's ORM?
- [Django]-Pycharm error Django is not importable in this environment
0π
Hereβs a hacky workaround for views.py when debug in settings.py is False
def my_style(request):
my_file = open('path to arbitrary css file', 'r')
response = HttpResponse(content=my_file.read())
response['Content-Type'] = 'text/css'
return response
and hereβs the urls.py
urlpatterns = [
path('hello', views.hello_world, name='hello_world'),
path('static/my_style/', views.my_style, name='my_style'),
]
And hereβs the insert for the html file
<link rel="stylesheet" type="text/css" href="static/my_style">
Though this is clearly not how Django was meant to be used, and Iβm guessing this could have some security implications.
- [Django]-Django 1.3.1 compilemessages. Error: sh: msgfmt: command not found
- [Django]-What is a good value for CONN_MAX_AGE in Django?
- [Django]-Django models ForeignKey on_delete attribute: full meaning?
0π
You can add CSS in Django Templates. *My answer explains how to load CSS and JavaScript files in Django.
For example, there is hello.css
in static/my_app1/css/
and there is index.html
in templates/
as shown below:
django-project
|-core
| β-settings.py
|-my_app1
|-my_app2
|-static
| β-my_app1
| β-js
| β-hello.css # Here
β-templates
β-index.html # Here
Then, set BASE_DIR / 'templates'
to DIRS in TEMPLATES and set BASE_DIR / 'static/'
in STATICFILES_DIRS in settings.py
as shown below so that Django can recognize templates
and static
folders just under django-project
. *My answer explains how to set Django Templates and I recommand to set whitenoise following my answer to disable your browser to cache the static files of Django:
# "settings.py"
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
BASE_DIR / 'templates' # Here
],
...
},
]
...
STATIC_URL = 'static/'
STATIC_ROOT = 'staticfiles/'
STATICFILES_DIRS = [
BASE_DIR / 'static/' # Here
]
Lastly, add <script ...></script>
to index.html
as shown below:
{# "index.html" #}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="{% static 'my_app1/css/hello.css' %}">
</head>
<body>
</body>
</html>
- [Django]-In a django model custom save() method, how should you identify a new object?
- [Django]-What is the purpose of apps.py in Django 1.9?
- [Django]-How to make Facebook Login possible in Django app ?