×
Community Blog How to Manage Django Images and Static Assets on Ubuntu 18.04

How to Manage Django Images and Static Assets on Ubuntu 18.04

This tutorial shows you how to effectively use the django.contrib.staticfiles module to improve web user experience with the Django framework.

By Bineli Manga, Alibaba Cloud Tech Share Author. Tech Share is Alibaba Cloud's incentive program to encourage the sharing of technical knowledge and best practices within the cloud community.

Any modern web application has a user-friendly interface through the use of CSS files, and displaying images and all this managed by JavaScript code. In the ecosystem of the Django framework, these three types of files (CSS, Images and Javascript) constitute the static files, and are entirely managed by this framework.

To manage these static files Django offers the module: django.contrib.staticfiles

In this tutorial, we will show you how to effectively use the django.contrib.staticfiles module to apply style sheets to HTML pages, how to display images on a web page, and how to improve user interactions by integrating JavaScript code with the Django framework.

To do this, we will create a small web application that will have a user profile page and a home page displaying multiple images.

Objectives

Here are the goals of the following tutorial

  • Show how to serve images and static files using the django framework
  • Show how to use the collectstatic command to deploy images and static files to production

Prerequisites

  • Have access to a computer or a virtual machine with ubuntu 18.04 installed
  • Have access to an IDE

Step 1: Initializing and Configuring the Project

1.1.  Environment Initialization

For the configuration of the development environment, we will follow the procedure presented here:

1.  Install necessary libraries

$ sudo apt install python3             # Install Python3 interpreter
$ sudo apt install python3-pip         # To manage python packages
$ sudo apt install python3-virtualenv  # To manage virtual python environments
$ sudo apt install apache2             # To serve images and static assets

2.  Create a virtual environment and activate it

$ virtualenv --python=python3 venv     # This create the virtual environment venv
$ source venv/bin/activate             # This is to activate the virtual environment

3.  Install project dependencies

(venv)$ pip install Django==2.1            # Install Django v2.1
(venv)$ pip install Pillow                 # To manage images through Python code
(venv)$ pip install easy_thumbnails        # To easyly manage image thumbnails

NB: The venv suffix is added to show that you are ruunning inside the isolated virtual environment named venv.

1.2.  Project Configuration

1.  Create the django project photogallery

(venv)$ django-admin startptoject photogallery

2.  Create the django application gallery

(venv)$ cd photogallery/
(venv)$ django-admin startapp gallery

3.  Add gallery app to the project photogallery

To do it, we have to add the gallery app to the settings.py file of the photogallery project.

INSTALLED_APPS = [
    ...
    'photogallery.gallery'
    ...
]

4.  Save migration data in the database

(venv)$ pyhton manage.py migrate

5.  Create a superuser for the django admin dashboard application

(venv)$ python manage.py createsuperuser --username admin
(venv)$ Email address: yourmail@web.com
(venv)$ Password:
(venv)$ Password (again):

6.  After executing this, here is the structure of the project folder

.
├── db.sqlite3
├── gallery
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── manage.py
└── socialgallery
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py

7.  Make sure that everything is working well

(venv)$ python manage.py runserver
...
Starting development server at http://127.0.0.1:8000/
...

Step 2: Configuring the Static Files Server

1.  Add the application django.contrib.staticfiles to INSTALLED_APPS inside the project's settings.py file:

INSTALLED_APPS = [
    ...
    'django.contrib.staticfiles'
    ...
]

2.  Create the folders for static files and set correct permissions

# Create static folders on the webserver
(venv)$ sudo mkdir /var/www/static
(venv)$ sudo mkdir /var/www/media
# Make static folders editable from the web browser
(venv)$ sudo chown -R www-data:www-data /var/www/static 
(venv)$ sudo chown -R www-data:www-data /var/www/media 
# Allow the group to write to the directory with appropriate permissions
(venv)$ sudo chmod -R 777 /var/www/static                   
(venv)$ sudo chmod -R 777 /var/www/media                   
# Add myself to the www-data group
(venv)$ sudo usermod -a -G www-data $(whoami)

3.  Configure the project for static files serving :

STATIC_URL = '/static/'              # Used to include static resources in web pages
STATIC_ROOT = '/var/www/static/'     # Used to get static resources from web server
MEDIA_URL = '/media/'                # Used to include media items in web pages
MEDIA_ROOT = '/var/www/media/'       # Used to get media items from web server

4.  Migrate images and static files from STATIC_URL to STATIC_ROOT and from MEDIA_URL to MEDIA_ROOT

# This command will copy everything from the STATIC_URL to the STATIC_ROOT
(venv)$ python manage.py collectstatic

NB : This command must be executed each time the application is deployed to take into account the new static files added by the users.

Step 3: Using Images and Static Files

To use image files and static files in a web page, it is necessary to pre-load the static module in the page concerned. To do this, add the following code to our root page base.html:

{% load static %}

Next, we can include imaes in our web pages by this way:

<img src={% static 'gallery/images/background.jpg' alt='Background Image' %}>

And we can add static assets to our web pages by including these tags:

{% static 'gallery/css/bootstrap.css'%}
{% static 'gallery/js/bootstrap.js'%}
{% static 'gallery/js/jquery.js'%}

Step 4: Data Model Definition

In order not to get away from the key topic, we will just create a single data model, for the management of images uploaded by a user.

1.  Here is the content of the file gallery/models.py

from django.db import models
from django.contrib.auth.models import User

class Image(models.Model):
    name = models.TextField(max_length='100')
    path = models.ImageField()
    number_views = models.IntegerField(default=0)

    def __str__(self):
        return self.name

2.  Save the model to the database

(venv)$ python manage.py make migrations    # This command will create migrations files
(venv)$ python manage.py migrate            # Here the migrations created are executed

Step 5: Writing Views

Views define how users interact with the application.

Views are created in the file : socialgallery/gallery/views.py

from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import ListView, CreateView, DetailView, \
     UpdateView, DeleteView
from .models import Image

class ImageListView(ListView):
    model = Image
    template_name = 'gallery/image_list.html'
    
class ImageDetailView(DetailView):
    model = Image
    template_name = 'gallery/image_detail.html'

class ImageCreateView(CreateView):
    model = Image
    template_name = 'gallery/image_create.html'
    fields = '__all__'

class ImageUpdateView(UpdateView):
    model = Image
    template_name = 'gallery/image_update.html'
    fields = '__all__'

class ImageDeleteView(DeleteView):
    model = Image
    template_name = 'gallery/image_delete.html'
    success_url = reverse_lazy('image-list')

Step 6: Defining the URLs

In order to access the views we created upthere, we have to set url routes. We will configure these routes inside the file gallery/urls.py, so if this folder doesn't exist on your app folder, make sur to create it before continuing.

Here is the content of the gallery/urls.py file:

from django.urls import path
from .views import ImageListView, ImageDetailView, ImageCreateView, \
    ImageUpdateView, ImageDeleteView

urlpatterns = [
    path('', ImageListView.as_view(), name='image-list'), # Will serve as homepage
    path('<int:pk>', ImageDetailView.as_view(), name='image-detail'),
    path('create', ImageCreateView.as_view(), name='image-create'),
    path('update/<int:pk>', ImageUpdateView.as_view(), name='image-update'),
    path('delete/<int:pk>', ImageDeleteView.as_view(), name='image-delete'),
]

Then we add the gallery/urls.py file to the project urls file photogallery/urls.py:

Here is the content of the file socialgallery/urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('images/', include('gallery.urls')),
]

Step 7: Creating HTML Templates

For the creation of HTML templates, we have to create the templates folder where Django will find the html templates we have specified in the views.py file.

(venv)$ mkdir gallery/templates templates/gallery 

Inside the gallery templates file, we create the following html files :

1.  templates/gallery/image_list.html

{% block content %}
    <h2>Images</h2>
    <ul>
        {% for image in object_list %}
            <li>{{ image.name }} - {{ image.path }} </li>
        {% endfor %}
    </ul>
{% endblock %}

2.  templates/gallery/image_detail.html

<p>Image</p>
<p>name: {{ object.name }}</p>
<p>Path: {{ object.path }}</p>
<p>Views: {{ object.number_views }}</p>

3.  templates/gallery/image_create.html

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save Image">
</form>

4.  templates/gallery/image_update.html

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Update User">
</form>

5.  templates/gallery/image_delete.html

<form method="post">
    {% csrf_token %}
    <p>Are you sure you want to delete the image "{{ object.name }}"?</p>
    <input type="submit" value="Confirm">
</form>

Step 8: Configure the Admin Dashboard

To configure the admin dashboard of the gallery app, we have to modify the gallery/admin.py file and add this code inside:

from django.contrib import admin
from .models import Image

@admin.register(Image)
class ImageAdmin(admin.ModelAdmin):
    model = Image

Step 9: Testing Everything Works Well

To test that everything works well, we need to launch our development server, using the command:

(venv)$ python manage.py runserver

Conclusion

Having reached the end of this tutorial, we have seen some cases of use of static resources in Django, their integration, their use and their service. We've seen what settings to consider when developing an application that manages images and how to ensure secure deployment of all these files.

Here is the link of the source code of the application that is online:

https://github.com/binel01/photogallery.git

For Further Reading

  • Package used for the management of images: django-easythumbnails, taking as reference the site Django packages
0 0 0
Share on

Alibaba Clouder

1,092 posts | 173 followers

You may also like

Comments

Alibaba Clouder

1,092 posts | 173 followers

Related Products