How to Create Static page in Django

Making your HTML pages visually appealing is really important. For that, you need to add some style to your pages using CSS or even do some programming with JavaScript. Both CSS and JavaScript run smoothly in your browser.

All you need is to send these files to the user. Let’s see how you can do it in a few steps with Django.

You rarely see sites serving static content (images, JavaScript, CSS) with Django because specialized tools work with it more effectively. However, for development purposes or even for your pet project with only a few visitors, you can serve content directly with Django.

Static files

HTML pages consist of three main parts:

  • HTML layout
  • CSS
  • JavaScript code

It’s convenient to define styles for pages in separate files to make our templates clear and easy to read. The same applies to JavaScript code. We know how to render templates, but how do we send other types of files to a client?

Creating static files

From your root directory, run the following commands in the terminal to create directories, or you can just use the GUI.

mkdir static 
mkdir static/css
mkdir static/js
mkdir static/img

Now you can move all your static assets here create a base.css file and add the stylesheet from the blog app there.

Let’s define a simple CSS file with just the properties for the h2 elements:

h2 {
  font-size: 24px;
  color: gray;
}

We save it to the file static/css/base.css relative to the root of the project. Also, you need to define a template in the blog/templates/blog/index.html file:

{% load static %}
<link rel="stylesheet" href="{% static 'css/base.css' %}">

<h2>{{ blog_name }}</h2>
<div>{{ post.text }}</div>

We use the tag {% load static %} to tell Django that we want to import an additional tag for the templates named static. After that, we use the tag {% static ‘css/base.css’ %} as a URL to the stylesheet for the page.

Note that we just utilize the css/base.css part for the required stylesheet; we discard the part of the URL that matches the STATIC_URL variable in the settings.py module.

In any case, if you attempt to launch the application utilizing this template, nothing happens to the style of the h2 element. We forgot to tell Django that we need to utilize it for serving static files! Add this to the end of your settings.py module:

DEBUG = True

STATIC_URL = "/static/"
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]

Extend your URL patterns in the urls.py module:

from django.conf import settings
from django.conf.urls.static import static

# your urlpatterns

urlpatterns += static(settings.STATIC_URL)

Now, you can launch the application once more, and serving static files will have exactly the intended effect! Your h2 element will have gray color, and if you need to change it, you may refer to the table with other color names supported by significant browsers.

The limitation for serving static files with Django is that it just works in DEBUG mode.

If your worker has some sensitive information or you stress that somebody will see data about your application and code in the debug trace, think about utilizing different methods to serve static files.

Media files

Besides HTML, a page may contain media files like images, videos, and audio files. To keep these files, we use the media folder on the server.

It usually includes all users’ media content that we keep on the server. Adding this path to your project is no harder than using static files.

First, we modify our settings.py module:

DEBUG = True

TEMPLATES[0]['OPTIONS']['context_processors'].append(
    'django.template.context_processors.media'
)

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

Then, extend URL patterns:

from django.conf import settings
from django.conf.urls.static import static

# your urlpatterns

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Now, create the media folder in the root of your project and place a picture in it with the name media/avatar.jpg. Finally, save the new content in your template:

<h2>{{ blog_name }}</h2>

<div>Here am I</div>
<img src="{{ MEDIA_URL }}/avatar.jpg" alt="avatar">

<div>{{ post.text }}</div>

Conclusion

Django provides you tools to fully cover the development process of a site, including serving static and media files. You can only use it in the debug mode, so it’s only a starting point for you.

To serve static files, configure your settings and URL patterns, and then add links to the content in your templates.

Now, try to solve this problem

Add a song from the file <media_folder>/mp3/django.mp3 to the template, where <media_folder> is a folder with media files.

Hint: You don’t need to know the exact name of the folder, use the appropriate variable to get the needed file.

template = """
<html>
  <audio src="{{ MEDIA_URL }}/mp3/django.mp3"></audio>
</html>
"""