In our last article, we have explained you how to use Django Framework to manage the process of file uploading. Now, in this tutorial, we are going to explain to perform the next step i.e. to handle or access the already uploaded static files using Django Framework. The static files could be an image file, CSS, JS, text file, etc.
So let us create a Django project to explain you how to use Django Framework to manage the static files which are already uploaded by the user. For those who have not read our last tutorials and for those who don't know how to create a Django project, here is a recap.
Creating a Django project
To create a directory for our project, we need to open the Command Prompt and type in the command -
dhago-admin is a management utility for Django Framework, using which we could create a new project and much more.
startproject is a command to start a new Django project.
django_static_file_handling is the name of our Django project and also the name of our project directory created in the current directory.
The startproject command gives us a sub-directory and files
Executing the startproject command has not only created a project directory named django_static_file_handling, but has also created a file manage.py and another sub-directory
with the same name as the project directory, which also contains some Python files -
django_static_file_handling is the root directory of our Django project, also known as the container of our project.
manage.py is a command-line utility which allows us to interact with Django project in various ways.
django_static_file_handling sub-directory is actually a Python package for our project. We can import this package(a group of modules) and its contents just like we import any general Python package/module and its contents.
__init__.py is a file which allows our sub-directory django_static_file_handling to be treated as a Python package.
settings.py is a file used for setting the configurations for our Django project.
urls.py is a file used to specify the URL declarations for our Django project, also known as a a table of contents.
wsgi.py is a file used as an entry-point for WSGI web-servers to serve your project.
Starting the development server
After creating the project directory and the files required to run our Django project, it is time to execute the Django Development Server. To do this,
we will have to open the command prompt, change the current directory to the root directory of our Django project and execute the following command.
python manage.py runserver
Executing the above mentioned command will trigger the Django Development Server in action, as you can see in the picture below.
E:\Django Projects\django_static_file_handling>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 16 unapplied migration(s). Your project may not work properly until you
apply the migrations for app(s): admin, auth, contenttypes.
Run 'python manage.py migrate' to apply them.
September 23, 2019 - 17:37:35
Django version 2.2.1, using settings 'django_static_file_handling.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Now that you have successfully started the Django development server, it is time to visit the http://127.0.0.1:8000/ link and you will see a webpage displaying a congratulatory message, as shown below.
Note: The runserver command runs the Django development server at the port 8000.
Important Steps:
Before proceeding further, we have to make sure that we follow the next two steps:
Make sure that django.contrib.staticfiles app is included in your INSTALLED_APPS, within the settings.py configuration file.
Make sure to define a property STATIC_URL within the within the settings.py configuration file, such as:
STATIC_URL = '/static/'
Creating an app in our project
A project may contain one or multiple applications. As we have already created a project, now let us create a welcome application in it which welcomes the user. This application will be created right under our root - project directory static_files.
To create an application, we have to open another window command prompt, change the current directory to the root directory of our Django project and execute the following command -
python manage.py startapp static_files
The command startapp in combination with manage.py utility is used to create an app of a project, using which we have created an app named - static_files_handling.
Executing the startapp command has not only created an application directory named static_files_handling in the root - project directory, but has also created the following set of Python files -
Next, we are going to create an HTML template file within our application folder static_files, we will name this file template.htm. An HTML template file contains the static part(comprising the HTML output) as well as some special syntax describing how the dynamic content will be inserted into this HTML file.
template.htm
<html>
<head><title>Django Handling Static - Decodejava.com</title></head>
{% load static %}
<link href="{% static 'upload/style.css' %}" rel="stylesheet">
<body>
<p>This is a cute kitty of our friend, isn't she cute?</p>
<img src="{% static '/upload/kitty.png' %}" height="150" width="300">
<script src="{% static '/upload/myscript.js' %}"></script>
<br/>
<br/>
<p>Play the sound of Cuckoo bird:</p>
<audio controls>
<source src="{% static '/upload/cuckoo.mp3' %}" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<br/>
<br/>
<p>Play a short fun video:</p>
<video width="320" height="240" controls>
<source src="{% static '/upload/small.mp4' %}" type="video/mp4">
Your browser does not support the video element.
</video>
</body>
</html>
{% load static %}
As shown in the code above, at the beginning of our template file, we have loaded the static template tag, which will be used to load the static files.
Next, we have used the static template tag to load a CSS stylesheet file named style.css by specifying its relative path This file is stored within the upload directory(which is within the static directory of the app).
<script src="{% static '/upload/myscript.js' %}">
Next, we have used the static template tag to load a script in Javascript named myscript.js by specifying its relative path. This file is stored within the upload directory(which is within the static directory of the app).
Next, we have used the static template tag within the HTML img tag to load an picture .png file named Tal2.png by specifying its relative path. This file is stored within the upload directory(which is within the static directory of the app).
<source src="{% static '/upload/cuckoo.mp3' %}">
Next, we have used the static template tag within the HTML audio tag to load an audio file named cuckoo.mp3 by specifying its relative path. This file is stored within the upload directory(which is within the static directory of the app).
<source src="{% static '/upload/small.mp4' %}">
Finally, we have used the static template tag within the HTML video tag to load an video MP4 file named small.mp4 by specifying its relative path. This file is stored within the upload directory(which is within the static directory of the app).
Note:
The path specified in the static tag is relative to the path specified in the property STATIC_URL within the within the settings.py.
Creating the view - view.py
Once we have created the HTML template file in the application, we will also need to create a view i.e. a view function.
This view function is simply a Python function which takes an HttpRequest from the HTML template file and returns an HttpResponse with the rendered the static files specified and requested by the HTML template file.
Note: This view functions are defined in the file view.py, which is already created and stored in our application directory, static_files. Let us just copy and paste the following code in view.py.
view.py
from django.shortcuts import render
# Create your views here.
def get_static_files(request):
return render(request,'template.htm')
Mapping URL to view
After creating the view function of an application, we need to specify the mapping between a URL and each view function in a file named - urls.py. The file urls.py is simply coded in Python and we will have to create the urls.py file in the folder of our application, static_files.
The use of mapping a URL to the view function is, when this URL is requested by the user, its mapped view function is executed and a response is returned.
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('static/', views.get_static_files),
]
As you can see in the file urls.py, we have imported the path() function from the module django.urls.
The path() function has been passed the two must arguments -
A string 'static/' is used to specify the URL pattern, this string will be matched to the view function - get_static_files.
Note:
This URL pattern specified in the application's urls.py file gets added to another URL pattern, specified in the project's urls.py file(we are going to create it next), and the combined path will be matched to the view functions defined in the application's views.py.
Pointing the project URL to application URL
Next, we are going to point the project URL(urls.py) to the application URL(urls.py) by using the include() function. For this, we will open the file urls.py in the root - project directory, django_static_file_handling, and copy-paste the following code.
urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('welcome/template/', include('static_files.urls')),
]
As you can see in the file urls.py, we have imported the path() and include() function from the module django.urls.
The path() function has been passed the two must arguments -
A string to specify the URL pattern - 'welcome/template/'. This is the relative path to the template.
This URL pattern, combined with the URL pattern defined in the application's urls.py will be matched to the view function - templ, which is specified in the application urls.py file(stored in the application directory static_files_handling). Therefore we have used the include() function to include and refer to the application's urls.py file.
How to load the HTML template file.
Next, we are going to show how to load the above created HTML template file template.htm, which is stored within our application folder static_files_handling.
To load the HTML template file, we need to specify its full path in the configuration file - settings.py, which is stored in the project folder. For our example, you can find this file in the project's sub-directory django_static_file_handling i.e. - django_static_file_handling/django_static_file_handling/settings.py.
Within the settings.py file, you need to locate the property DIRS and copy-paste the full-path to the HTML template file against it, as shown below and save the file.
And finally, it's time to execute our Django project with templates.
Executing the application of our project
To execute the static_files application of our project django_static_file_handling, we just have to enter the address - http://127.0.0.1:8000/welcome/template/static. This displays the webpage with an alert from
Javascript static file being loaded.
Next, on clicking the OK button, the webpage loads all the requested static files:
A CSS stylesheet.
An image file
An audio file.
A video file
This concludes the tutorial of how using Django we can manage the already uploaded static files. See you in the next one!