Manage Django images and static assets on Ubuntu

This tutorial will show you how to effectively use the ** django **. Contrib.staticfiles module to improve the web user experience with the ** Django ** framework.

Purpose

The goals of the tutorial below are:

--Shows how to serve images and static files using the django framework. --Shows how to deploy images and static files to production using the collectstatic command.

Prerequisites

--Accessing a computer or virtual machine with ubuntu 18.04 installed --Access to the IDE

Step 1: Initialize and configure the project

1.1. Initializing the environment

To set up the development environment, follow the procedure introduced here.

1, installation of required 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
  1. Create and activate a virtual environment
$ virtualenv --python=python3 venv     # This create the virtual environment venv
$ source venv/bin/activate             # This is to activate the virtual environment

3, project dependency installation

(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

** Note **: A venv suffix has been added to indicate ruunning in an isolated virtual environment named venv.

1.2. Project settings

  1. Create a ** photo gallery ** for your django project
(venv)$ django-admin startptoject photogallery

2, create a django application ** gallery **

(venv)$ cd photogallery/
(venv)$ django-admin startapp gallery
  1. Add ** Gallery ** app to ** Photo Gallery ** of the project

To do this, you need to add the Gallery app to your photo gallery project's settings.py file.

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

4, save the 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: [email protected]
(venv)$ Password:
(venv)$ Password (again):
  1. When you do this, the structure of the project folder will be as follows.
.
├── 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 everything is working fine.

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

Step 2: Set up a static file server

  1. Add the application ** django.contrib.staticfiles ** to ** INSTALLED_APPS ** in the project's ** settings.py ** file.
INSTALLED_APPS = [
    ...
    'django.contrib.staticfiles'
    ...
]
  1. Create a folder for static files and set the 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 to serve static files.

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

** Note **: This command must be run every time the application is deployed considering the new static files added by the user.

Step 3: Use images and static files

To use image or static files on a web page, you need to preload the static module on that page. To do this, add the following code to ** base.html ** on the root page.

{% load static %}

Next, you can put your image on your homepage in this way.

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

And by including these tags, you can add static assets to your web pages.

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

Step 4: Define the data model

Staying on top of the subject, we'll create just one data model to manage the images uploaded by users.

1, The following is the contents of the ** gallery / models.py ** file.

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 in 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: How to write a view

Views define how users interact with your 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: Define URL

In order to access the view created here, you must set the URL root. These roots are set in the ** gallery / urls.py ** file, so if this folder doesn't exist in your app's folder, create it before continuing.

The contents of the ** gallery / urls.py ** file are as follows.

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 add the ** gallery / urls.py ** file to your project's urls file ** photogallery / urls.py **.

Below is the contents 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: Create HTML template

To create an HTML template, you need to create a template folder where Django will find the HTML template you specified in the ** views.py ** file.

(venv)$ mkdir gallery/templates templates/gallery 

Create the following html file in the gallery template file.

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: Admin Dashboard Settings

To set up the gallery app admin dashboard, you must modify the ** gallery / admin.py ** file to add this code internally.

from django.contrib import admin
from .models import Image

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

Step 9: Test if everything works

To test that everything works, you need to use the command to start the development server.

(venv)$ python manage.py runserver

Conclusion

You've come to the end of this tutorial to see examples, integrations, uses, and services of using static resources in Django. We have seen the settings to consider when developing an image management application and how to ensure a secure deployment of all these files.

Below is a link to the source code of the application published online.

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

read more

--Packages used to manage images: django-easythumbnails, Django Packages.

Recommended Posts

Manage Django images and static assets on Ubuntu
Install Mecab and mecab-python3 on Ubuntu 14.04
Install and run dropbox on Ubuntu 20.04
Install OpenCV and Chainer on Ubuntu
Install CUDA 8.0 and Chainer on Ubuntu 16.04
Install fabric on Ubuntu and try
Build Python3 and OpenCV environment on Ubuntu 18.04
Python virtual environment and packages on Ubuntu
Notes on creating static files in Django
Mount and format Disk on Ubuntu on GCP.
Install Puppet Master and Client on Ubuntu 16.04
Install pyenv and Python 3.6.8 on Ubuntu 18.04 LTS
Django: Record User Agent and manage with Admin
Deploy Django apps on Ubuntu + Nginx + MySQL (Build)
Let's integrate Django and apache (httpd) on Mac! !!
[Django] About static file related settings (images, videos)
Install MongoDB on Ubuntu 16.04 and operate via python
Shebang on Ubuntu 20.04
Install Apache 2.4 on Ubuntu 19.10 Eoan Ermine and run CGI
Ubuntu 20.04 on raspberry pi 4 with OpenCV and use with python
Dealing with pip and related installation errors on Ubuntu 18.04
Install django on python + anaconda and start the server
Set up python and machine learning libraries on Ubuntu