Python and Django Full Stack - Include Image and CSS References
In the previous blog post, we looked at template tags to render custom text. In this post, we will see how to refer to images and css files.
The steps are the same as for
template tags, except for the following differences:
1.
Create a folder called static in the top level project
folder. Inside the static directory, create two folders -
i. images to store the pictures. (save any picture e.g. mypicture.jpg in this directory)
ii. css to store the css file (e.g. mystyles.css)
i. images to store the pictures. (save any picture e.g. mypicture.jpg in this directory)
ii. css to store the css file (e.g. mystyles.css)
2. Include this
folder to the settings.py file, so Django knows where to find it. Note that the variable STATIC_URL comes pre-defined from versions 1.9 and up. Ensure there are no duplicate declarations of the variables.
STATIC_URL = 'static/'
STATICFILES_DIRS = [
'static',
]
3.
Test if this works, by going to 127.0.0.1:8000/static/images/mypicture.jpg.
This will confirm the paths are set up correctly.
4.
Now, we set up a template tag for this.
5.
At the top of the html file, add a specific tag
{% load static%} just below <!DOCTYPE html> tag
6.
Insert the image where you want it in the html
file with the tag
<img src={{%static “images/mypicture.jpg%} />
Notice that the image template tag is {%%}, different from the text template {{}}
<img src={{%static “images/mypicture.jpg%} />
Notice that the image template tag is {%%}, different from the text template {{}}
7. To also include a css file, create a css folder
under /static. Under static/css, create a css file (e.g. mystyle.css). In the
index.html file, define it using the “<link>” tag as shown below:
<!DOCTYPE html>
{%
load static%} //include this
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>First App</title>
<link rel="stylesheet" href="{% static "css/mystyle.css"
%}" />
</head>
<body>
<h1>Hello, this is a picture of Django himself from
index.html</h1>
<img src = "{%
static "images/django.jpg"%}" alt = "Uh Oh,
didn't show">
</body>
</html>
Comments
Post a Comment