This tutorial will show you how to effectively use the ** django **. Contrib.staticfiles module to improve the web user experience with the ** Django ** framework.
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.
--Accessing a computer or virtual machine with ubuntu 18.04 installed --Access to the IDE
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
$ 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.
(venv)$ django-admin startptoject photogallery
2, create a django application ** gallery **
(venv)$ cd photogallery/
(venv)$ django-admin startapp gallery
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):
.
├── 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/
...
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)
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
# 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.
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'%}
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
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')
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')),
]
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>
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
To test that everything works, you need to use the command to start the development server.
(venv)$ python manage.py runserver
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
--Packages used to manage images: django-easythumbnails, Django Packages.
Recommended Posts