Django – Static Files Inserting Static Media Files

Django is a Python based web framework. It uses a model-template-view architecture. Goals of Django Framework are reusability, fast development, less code and the principle of “Don’t repeat yourself”.In this blog, we will discuss the topic of Django which is “How to insert static media files”.Static files can be an image file, a CSS file or it can be a JavaScript.

Django has Template Syntax for insertion of content in HTML pages. We will see two types of bracket syntax in Django’s template. This {{ simple_text }} is being used for simple text injection, and we can use {% %} for complex injections and logic. Now let’s start with our tutorial.

Note: In this tutorial I have used visual studio code for implementation. So all the snapshots are of visual studio code.

In this tutorial we will insert image as static media file into our webpage. To do this, we will create a new directory inside of the project called “static”. For example you have to make folder in this directory: “Your_Project_name\static”. You can see the same in the snapshot given below.

Then we will add this directory path to the project’s settings.py file and also add a STATIC_URL variable which is already given by default in new version of django.

After this we create a directory under the static folder called images to store static image files. As of now we will not use database to store image files so that we have created above file directory.

settings.py

Now place the jpg image files which you want to insert in webpage inside the “myblog\static\images” directory. Now we will actually injecting this image file into our simple html page using tamplate tagging.

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_DIR = os.path.join(BASE_DIR,"static")
TEMPLATES_DIR = os.path.join(BASE_DIR,"templates") 

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATES_DIR],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

STATIC_URL = '/static/'
STATICFILES_DIR = [
   STATIC_DIR,
]

For html file we have to create “template” folder and inside this folder we will create one more folder, name of this folder will same as our application name eg.”blog”, Now inside this folder we will create HTML file named “index.html”. Process is same, as we have done for “static” folder. Please refer settings.py code for template making.

Now make connection of index.html file with valid url. For this first of all create view named “index” in views.py of our app.

views.py

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
    return render(request,'demo\index.html')

And set path for index view in “urls.py” of our project folder.

urls.py

from django.contrib import admin
from django.urls import path
from demo import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index),
]

Now let’s come to final part of our tutorial. Now we will write html in index.html file. To insert static files inside a html file, we will add some special tags, at the top:

  • {% load staticfiles %} or {% load static %} for newer versions

Then we insert the image with a HTML tag:

  • <img src = {%static “images/pic.jpg” %} />

index.html

<!DOCTYPE html>
{% load static %}
<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>index</title>
</head>

<body>
    <h1>This is a picture.</h1>
    <img src="{% static " images/django.jpg" %}" alt="">

</body>

</html>

Now let’s run the server using “python manage.py runserver” command and see the magic!!

Django – Inserting Static Media Files

So that’s all about this tutorial.

You may also like :

How to create Built-In Change Password and Reset Password in Django

How to Send Email in Django