Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include external css, image, etc in django template?

Tags:

python

django

In django, all urls are parsed from urls.py file. So, there is no directory structure as such.

So, what if you have to include a css file in your template ?

Is there a way without adding it to url.py file ?

If no, then will you make new entry in urls.py for every resource ?

like image 345
Yugal Jindle Avatar asked Aug 15 '11 12:08

Yugal Jindle


People also ask

How do I include image files in Django templates?

In django we can deal with the images with the help of model field which is ImageField . In this article, we have created the app image_app in a sample project named image_upload. The very first step is to add below code in the settings.py file. MEDIA_ROOT is for server path to store files in the computer.

Can we use CSS in Django?

Including CSS in Django TemplateWe need to load the static files by adding the below line of code at the top of the template (. HTML) file. Then, insert the stylesheet in the HTML using link HTML tag. If you are new to the HTML and CSS, you can learn more about adding CSS in HTML code.

Where are Django CSS files stored?

css . In other words, your stylesheet should be at polls/static/polls/style. css . Because of how the AppDirectoriesFinder staticfile finder works, you can refer to this static file in Django as polls/style.


2 Answers

See the Django HOWTO on static files.

Basically, in your configuration file, you specify a special directory to store static files in. The example in the docs is:

STATIC_ROOT = "/home/jacob/projects/mysite.com/sitestatic"

You put CSS files, images, etc. in there, and the server will know to serve URLs that match your static URL pattern from that directory.

like image 126
agf Avatar answered Oct 19 '22 19:10

agf


You no longer need to specify STATIC_ROOT (for djangor > 1.10). Simply, make sure

django.contrib.staticfiles

is included in INSTALLED_APPS

and

STATIC_URL = '/static/'

in your settings.py

Create a directory called "static" in your app directory, and inside the created static directory, another subdirectory named your app and include the static files there (you could also create js, img, css subdirectories inside the last directory based on your preference if you need)

Then, include the correct path in the template file. For ex:

src = "/static/my_app/example.js"

or

src = "/static/my_app/js/example.js"

(assuming your javascript files are in a directory called js)

Alternatively (much better), define the path using the static template tag:

{% load static %}
<script src="{% static "my_app/js/example.js" %}"></script>

All you need to know:

https://docs.djangoproject.com/en/1.10/howto/static-files/

like image 4
picmate 涅 Avatar answered Oct 19 '22 18:10

picmate 涅