How to Manage Django Images and Static Assets on Ubuntu 18.04

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:

$ 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
$ virtualenv --python=python3 venv     # This create the virtual environment venv
$ source venv/bin/activate # This is to activate the virtual environment
(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

1.2. Project Configuration

1. Create the django project photogallery

(venv)$ django-admin startptoject photogallery
(venv)$ cd photogallery/
(venv)$ django-admin startapp gallery
INSTALLED_APPS = [
...
'photogallery.gallery'
...
]
(venv)$ pyhton manage.py migrate
(venv)$ python manage.py createsuperuser --username admin
(venv)$ Email address: yourmail@web.com
(venv)$ Password:
(venv)$ Password (again):
.
├── 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
(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'
...
]
# 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)
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
# This command will copy everything from the STATIC_URL to the STATIC_ROOT
(venv)$ python manage.py collectstatic

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 %}
<img src={% static 'gallery/images/background.jpg' alt='Background Image' %}>
{% 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.

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
(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.

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.

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'),
]
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
{% block content %}
<h2>Images</h2>
<ul>
{% for image in object_list %}
<li>{{ image.name }} - {{ image.path }} </li>
{% endfor %}
</ul>
{% endblock %}
<p>Image</p>
<p>name: {{ object.name }}</p>
<p>Path: {{ object.path }}</p>
<p>Views: {{ object.number_views }}</p>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save Image">
</form>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update User">
</form>
<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.

For Further Reading

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

Reference

https://www.alibabacloud.com/blog/how-to-manage-django-images-and-static-assets-on-ubuntu-18-04_594696?spm=a2c41.12784921.0.0

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alibaba Cloud

Alibaba Cloud

Follow me to keep abreast with the latest technology news, industry insights, and developer trends. Alibaba Cloud website:https://www.alibabacloud.com