Add documentation and source

Added documentation, source and extra files.
This commit is contained in:
2025-07-02 20:26:50 +02:00
parent 4fc1d36a10
commit e3ebf6bf4f
295 changed files with 24986 additions and 0 deletions

31
source/README.md Normal file
View File

@ -0,0 +1,31 @@
# Projets de démo Django
Chacun des répertoires ci-dessous peut être récupéré comme projet Django, à savoir :
- `advanced` : fonctions avancées (URL téléchargement)
- `authentication` : bouts de code pour gérer les utilisateurs
- `forms` : test des formulaires
- `orm` : projet d'interface utilisant des données en base
- `templating` : utilisation du langage de templates
- `translation` : traduction
Les répertoires contiennent un fichier `manage.py` et peuvent être lancés avec la commande habituelle :
```bash
python manage.py runserver
```
Vérifiez quand même les fichiers `urls.py` pour savoir quelles URLs sont disponibles pour chaque projet (l'un d'entre eux ne répond pas à l'URL http://127.0.0.1/ mais répond à d'autres URLs).
---
Les répertoires de projet peuvent être ouverts avec PyCharm (contiennent un répertoire `.idea`). Vous devrez peut-être créer un environnement virtuel pour ces projets. Pour cela :
- rendez-vous dans le menu `File``Settings`
- dans la catégorie `Project``Python Interpreter`, vérifiez que l'interpréteur est dans un répertoire relatif à votre projet, ou créez un nouvel interpréteur `virtualenv`.
Avant de pouvoir exécuter le projet, vous devez installer les dépendances présentes dans requirements.txt :
```{.bash .numberLines}
pip install -r requirements.txt
```

0
source/__init__.py Normal file
View File

31
source/advanced/.idea/Advanced.iml generated Normal file
View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="FacetManager">
<facet type="django" name="Django">
<configuration>
<option name="rootFolder" value="$MODULE_DIR$" />
<option name="settingsModule" value="advanced/settings.py" />
<option name="manageScript" value="manage.py" />
<option name="environment" value="&lt;map/&gt;" />
<option name="doNotUseTestRunner" value="false" />
<option name="trackFilePattern" value="" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/.idea" />
<excludeFolder url="file://$MODULE_DIR$/jupyter/.ipynb_checkpoints" />
</content>
<orderEntry type="jdk" jdkName="Python 3 (training)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="GOOGLE" />
<option name="myDocStringFormat" value="Google" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Django" />
</component>
</module>

View File

@ -0,0 +1,12 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="GrazieInspection" enabled="false" level="TYPO" enabled_by_default="false" />
<inspection_tool class="LanguageDetectionInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false">
<option name="processCode" value="true" />
<option name="processLiterals" value="true" />
<option name="processComments" value="true" />
</inspection_tool>
</profile>
</component>

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

8
source/advanced/.idea/modules.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/advanced.iml" filepath="$PROJECT_DIR$/.idea/advanced.iml" />
</modules>
</component>
</project>

11
source/advanced/.idea/workspace.xml generated Normal file
View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showExcludedFiles" value="false" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">
<property name="settings.editor.selected.configurable" value="configurable.group.tools" />
</component>
</project>

View File

View File

@ -0,0 +1,16 @@
"""
ASGI config for advanced project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'advanced.settings')
application = get_asgi_application()

View File

@ -0,0 +1,139 @@
"""
Django settings for advanced project.
Generated by 'django-admin startproject' using Django 3.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-4f#(qt450m(73!m#q%6jhl*t@0_%xn4$)ing$)-2qey-^bv*xy"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django_extensions",
"various",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"django.middleware.locale.LocaleMiddleware",
]
ROOT_URLCONF = "advanced.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "advanced.wsgi.application"
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "database.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = "/static/"
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
# Email configuration
# Set a backend in console for demonstration purposes.
# The correct backend should be SMTP in production.
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
# Media configuration
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"

View File

@ -0,0 +1,26 @@
"""advanced URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path
from various.views import view_file_download
urlpatterns = [
path("admin/", admin.site.urls),
path("download", view_file_download, name="download"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

View File

@ -0,0 +1,16 @@
"""
WSGI config for advanced project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'advanced.settings')
application = get_wsgi_application()

Binary file not shown.

View File

@ -0,0 +1,81 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"id": "fc76bc88",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Content-Type: text/plain; charset=\"utf-8\"\n",
"MIME-Version: 1.0\n",
"Content-Transfer-Encoding: 7bit\n",
"Subject: Title\n",
"From: noreply@example.aa\n",
"To: noreply@example.aa\n",
"Date: Fri, 16 Apr 2021 22:44:20 -0000\n",
"Message-ID: <161861306067.29777.1833249302107691814@manjaro>\n",
"\n",
"Body of the email.\n",
"-------------------------------------------------------------------------------\n"
]
},
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Simple example to send a text email\n",
"from django.core.mail import send_mail\n",
"send_mail(\"Title\", \"Body of the email.\", \"noreply@example.aa\", [\"noreply@example.aa\"])"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "badac700",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Maggle\n"
]
}
],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Django Shell-Plus",
"language": "python",
"name": "django_extensions"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.2"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

22
source/advanced/manage.py Normal file
View File

@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'advanced.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

View File

@ -0,0 +1,9 @@
from django.apps import AppConfig
class VariousConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "various"
default_app_config = "various.VariousConfig"

View File

@ -0,0 +1 @@
from .room import *

View File

@ -0,0 +1,51 @@
from django.contrib import admin
from django.db import models
from django.db.models import F
from django.http import HttpRequest
from django.utils.translation import gettext_lazy as _
from various.models import Room
@admin.register(Room)
class RoomAdmin(admin.ModelAdmin):
"""
Admin configuration for rooms.
"""
list_display = ["id", "name", "length", "width", "height", "get_volume_display"]
list_editable = ["name", "length", "width", "height"]
actions = ["action_fix_minimum"]
def get_queryset(self, request):
"""
Change queryset to add a computed field for volume.
Args:
request: HTTP
"""
return super().get_queryset(request).annotate(volume=F("width") * F("length") * F("height"))
def get_volume_display(self, obj: Room) -> str:
return f"{obj.get_volume()} cm³"
get_volume_display.short_description = _("area")
get_volume_display.admin_order_field = "volume"
def action_fix_minimum(self, request: HttpRequest, queryset: models.QuerySet):
"""
Change room dimensions to have at least 1cm in every axis.
Args:
request: HTTP request.
queryset: selected rooms.
"""
for room in queryset: # type: Room
room.width = max(1, room.width)
room.length = max(1, room.length)
room.height = max(1, room.height)
room.save()
self.message_user(request, _("The selected rooms have been updated."))

View File

@ -0,0 +1,59 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2021-04-18 11:30+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
#: various/admin/room.py:34
msgid "area"
msgstr "aire"
#: various/admin/room.py:51
msgid "The selected rooms have been updated."
msgstr "Les salles sélectionnées ont été mises à jour."
#: various/models/room.py:11
msgid "name"
msgstr "nom"
#: various/models/room.py:12
msgid "description"
msgstr "description"
#: various/models/room.py:13 various/models/room.py:14
#: various/models/room.py:15
msgid "centimeters"
msgstr "centimètres"
#: various/models/room.py:13
msgid "width"
msgstr "largeur"
#: various/models/room.py:14
msgid "length"
msgstr "longueur"
#: various/models/room.py:15
msgid "height"
msgstr "hauteur"
#: various/models/room.py:18
msgid "room"
msgstr "salle"
#: various/models/room.py:19
msgid "rooms"
msgstr "salles"

View File

@ -0,0 +1,29 @@
# Generated by Django 3.2 on 2021-04-18 11:28
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Room',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=32, unique=True, verbose_name='name')),
('description', models.TextField(blank=True, verbose_name='description')),
('width', models.PositiveIntegerField(default=0, help_text='centimeters', verbose_name='width')),
('length', models.PositiveIntegerField(default=0, help_text='centimeters', verbose_name='length')),
('height', models.PositiveIntegerField(default=0, help_text='centimeters', verbose_name='height')),
],
options={
'verbose_name': 'room',
'verbose_name_plural': 'rooms',
},
),
]

View File

@ -0,0 +1 @@
from .room import *

View File

@ -0,0 +1,49 @@
from django.db import models
from django.utils.translation import gettext_lazy as _
class Room(models.Model):
"""
Room definition.
"""
name = models.CharField(max_length=32, blank=False, unique=True, verbose_name=_("name"))
description = models.TextField(blank=True, verbose_name=_("description"))
width = models.PositiveIntegerField(default=0, help_text=_("centimeters"), verbose_name=_("width"))
length = models.PositiveIntegerField(default=0, help_text=_("centimeters"), verbose_name=_("length"))
height = models.PositiveIntegerField(default=0, help_text=_("centimeters"), verbose_name=_("height"))
class Meta:
verbose_name = _("room")
verbose_name_plural = _("rooms")
def get_area(self) -> int:
"""
Get the area of the room.
Returns:
Area of the room in square centimeters.
"""
return self.width * self.length
def get_volume(self) -> int:
"""
Get the volume of the room.
Returns:
Volume of the room in cube centimeters.
"""
return self.width * self.length * self.height
def is_empty(self) -> bool:
"""
Tell if the room is empty (has no volume).
Returns:
Whether the room has no volume (zero).
"""
return self.width * self.length * self.height == 0

View File

@ -0,0 +1 @@
from .room import *

View File

@ -0,0 +1,55 @@
from django import test
from various.models import Room
class RoomTestCase(test.TestCase):
"""
Basic test case for rooms.
This method is executed before every `test_` function.
To run those automatic tests, in a terminal, just run
`./manage.py test`
"""
def setUp(self) -> None:
self.room1 = Room(name="Kitchen", width=260, length=320, height=250) # basic
self.room2 = Room(name="Fake", width=0, length=320, height=250) # a 2D object
@classmethod
def setUpClass(cls):
"""Cette méthode est exécutée une seule fois avant ous les tests."""
pass
@classmethod
def tearDownClass(cls):
pass
def tearDown(self) -> None:
"""
End unit test.
Is executed after every `test_` method.
"""
def test_base_room(self):
"""
Basic test using the fixture set up in the `setUp` method.
"""
self.assertEqual(self.room2.get_volume(), 0)
self.assertEqual(self.room1.get_area(), 83200)
def test_dummy_page(self):
"""
Test the Django test client.
Used to test that pages of the projet answer properly.
"""
client = test.Client()
response = client.get("/admin/")
self.assertNotEqual(response.status_code, 404)

View File

@ -0,0 +1,21 @@
from django.core.files.storage import DefaultStorage
from django.http import HttpRequest, HttpResponse
def view_file_download(request: HttpRequest) -> HttpResponse:
"""
Serve a media file like a download.
Args:
request: HTTP request.
Returns:
Media file as an attachment to download.
"""
storage = DefaultStorage() # Objet capable de manipuler des fichiers média
with storage.open("django-upload.jpg", "rb") as file: # relative to MEDIA_ROOT
response = HttpResponse(file, content_type="image/jpeg")
# Use list notation to set headers
response["Content-Disposition"] = "attachment; filename=django-upload.jpg"
return response

View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="FacetManager">
<facet type="django" name="Django">
<configuration>
<option name="rootFolder" value="$MODULE_DIR$" />
<option name="settingsModule" value="authentication/settings.py" />
<option name="manageScript" value="manage.py" />
<option name="environment" value="&lt;map/&gt;" />
<option name="doNotUseTestRunner" value="false" />
<option name="trackFilePattern" value="" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/.idea" />
</content>
<orderEntry type="jdk" jdkName="Python 3 (training)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="GOOGLE" />
<option name="myDocStringFormat" value="Google" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Django" />
</component>
</module>

View File

@ -0,0 +1,12 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="GrazieInspection" enabled="false" level="TYPO" enabled_by_default="false" />
<inspection_tool class="LanguageDetectionInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false">
<option name="processCode" value="true" />
<option name="processLiterals" value="true" />
<option name="processComments" value="true" />
</inspection_tool>
</profile>
</component>

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

8
source/authentication/.idea/modules.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/authentication.iml" filepath="$PROJECT_DIR$/.idea/authentication.iml" />
</modules>
</component>
</project>

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showExcludedFiles" value="false" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">
<property name="settings.editor.selected.configurable" value="configurable.group.tools" />
</component>
</project>

Binary file not shown.

View File

@ -0,0 +1,16 @@
"""
ASGI config for authentication project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'authentication.settings')
application = get_asgi_application()

View File

@ -0,0 +1,130 @@
"""
Django settings for authentication project.
Generated by 'django-admin startproject' using Django 3.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-fjg#b7qx5e5g3e2vcfb@eg9b3!xy1c+nix5*y=k7h6j&&pc)e8"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"users",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "authentication.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "authentication.wsgi.application"
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "authentication.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = "/static/"
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
# Authentication settings
LOGIN_REDIRECT_URL = "/profile"

View File

@ -0,0 +1,27 @@
"""authentication URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from users.views import view_user, view_authentication_code
urlpatterns = [
path("admin/", admin.site.urls),
# https://docs.djangoproject.com/fr/3.1/topics/auth/default/#module-django.contrib.auth.views
path("", include("django.contrib.auth.urls")),
path("profile", view_user),
path("codedemo", view_authentication_code),
]

View File

@ -0,0 +1,16 @@
"""
WSGI config for authentication project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'authentication.settings')
application = get_wsgi_application()

View File

@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'authentication.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

View File

@ -0,0 +1,9 @@
from django.apps import AppConfig
class UsersConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "users"
default_app_config = "users.UsersConfig"

View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="" method="post" name="login-form">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="login-button" value="Login">
</form>
</body>
</html>

View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User</title>
</head>
<body>
{% if user.is_anonymous %}
You are not connected with a user.
{% else %}
Welcome, you are connected as {{ user.username }}
{% endif %}
</body>
</html>

View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User</title>
</head>
<body>
{% if user.is_anonymous %}
You are not connected with a user.
{% else %}
Welcome, you are connected as {{ user.username }}
{% endif %}
</body>
</html>

View File

@ -0,0 +1,22 @@
from annoying.decorators import render_to
from django.contrib.auth import login, logout, authenticate
@render_to("users/user-page.html")
def view_user(request):
return {}
@render_to("users/user-code-page.html")
def view_authentication_code(request):
# First, logout if we're already connected
logout(request)
# Show that we have no connected user session for the request
print(request.user)
# Check authentication with the current settings
user = authenticate(username="root", password="root")
# A user is returned only if the credentials are correct
if user is not None:
# Login the obtained user in the request
login(request, user)
return {"auth_user": user}

33
source/forms/.idea/Forms.iml generated Normal file
View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="FacetManager">
<facet type="django" name="Django">
<configuration>
<option name="rootFolder" value="$MODULE_DIR$" />
<option name="settingsModule" value="forms/settings.py" />
<option name="manageScript" value="manage.py" />
<option name="environment" value="&lt;map/&gt;" />
<option name="doNotUseTestRunner" value="false" />
<option name="trackFilePattern" value="" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/.idea" />
</content>
<orderEntry type="jdk" jdkName="Python 3 (training)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PackageRequirementsSettings">
<option name="requirementsPath" value="$MODULE_DIR$/../../requirements.pip" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="GOOGLE" />
<option name="myDocStringFormat" value="Google" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Django" />
</component>
</module>

View File

@ -0,0 +1,12 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="GrazieInspection" enabled="false" level="TYPO" enabled_by_default="false" />
<inspection_tool class="LanguageDetectionInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false">
<option name="processCode" value="true" />
<option name="processLiterals" value="true" />
<option name="processComments" value="true" />
</inspection_tool>
</profile>
</component>

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

8
source/forms/.idea/modules.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/forms.iml" filepath="$PROJECT_DIR$/.idea/forms.iml" />
</modules>
</component>
</project>

8
source/forms/.idea/workspace.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showExcludedFiles" value="false" />
<option name="showLibraryContents" value="true" />
</component>
</project>

View File

@ -0,0 +1,9 @@
from django.apps import AppConfig
class DemonstrationConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "demonstration"
default_app_config = "demonstration.DemonstrationConfig"

View File

@ -0,0 +1,3 @@
from .person import PersonForm
from .search import SearchForm
from .upload import UploadForm

View File

@ -0,0 +1,13 @@
from datetime import date
from django import forms
class PersonForm(forms.Form):
"""Example of form for person information."""
first_name = forms.CharField(max_length=32, label="first name")
last_name = forms.CharField(max_length=32, label="last name")
birth_date = forms.DateField(initial=date(1990, 1, 1), label="birthday")
phone_number = forms.CharField(max_length=12, label="phone number")
password = forms.CharField(widget=forms.PasswordInput, max_length=50, label="password")

View File

@ -0,0 +1,24 @@
from typing import List
from django import forms
from django.core.exceptions import ValidationError
class SearchForm(forms.Form):
"""Example of search form."""
FORBIDDEN_WORDS: List[str] = ["lemon", "hat", "car"]
query = forms.CharField(max_length=32, label="query", required=True)
def clean_query(self) -> str:
"""
Validate the query field.
Returns:
The value for the "cleaned" query field.
"""
value: str = self.cleaned_data["query"]
if value.lower() in self.FORBIDDEN_WORDS:
raise ValidationError(f"Search term cannot be one of the following: {self.FORBIDDEN_WORDS}")
return value

View File

@ -0,0 +1,26 @@
from django import forms
from django.core.files.storage import FileSystemStorage
from django.http import HttpRequest
class UploadForm(forms.Form):
"""Example of file upload form."""
image = forms.ImageField(max_length=128, required=True, label="image")
@staticmethod
def save_uploaded_file(request: HttpRequest) -> str:
"""
Custom method to process the upload of the image.
Args:
request: HTTP request.
Returns:
URL of the new uploaded image.
"""
storage = FileSystemStorage()
image = request.FILES["image"]
name = storage.save(None, image)
return storage.url(name)

View File

@ -0,0 +1,77 @@
:root {
--head-bg-color: #222;
--head-fg-color: #fff;
--head-ln-color: #3cf;
}
html, body {
height: 100%;
min-height: 100%;
width: 100%;
}
body {
margin: 0;
display: grid;
grid-template-areas: "header" "content" "footer";
grid-template-rows: auto 1fr auto;
grid-template-columns: 100%;
font-family: "Roboto", "Lucida Grande", "DejaVu Sans", "Bitstream Vera Sans", Verdana, Arial, sans-serif;
}
section#header {
grid-area: header;
}
section#content {
grid-area: content;
}
section#footer {
grid-area: footer;
}
section#header, section#footer {
background-color: var(--head-bg-color);
color: var(--head-fg-color);
}
section#header a, section#footer a {
color: var(--head-ln-color);
text-decoration: none;
}
div.body {
width: 1024px;
margin: 1.5em auto;
}
table.form-table {
width: 100%;
}
table.form-table th {
text-align: left;
}
table.form-table td {
text-align: right;
}
table.form-table td > input[type=text] {
width: 100%;
box-sizing: border-box;
}
input[type=submit] {
padding: 0.5em 4em;
margin: 0;
background-color: crimson;
color: white;
font-size: 125%;
border: maroon 1px solid;
border-radius: 0.5em;
box-shadow: coral 0 0 0 1px inset;
}

View File

@ -0,0 +1,33 @@
{% load static %} {# The load tag enables template tags from other Django apps #}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %} | Django Demonstration{% endblock title %}</title>
<link rel="stylesheet" href="{% static "demonstration/demonstration.css" %}">
</head>
<body>
<section id="header">
<div class="body">
<nav>
<a href="/">Home page</a>
</nav>
</div>
</section>
<section id="content">
<div class="body">
{% block body %}
Base content in a overridable block.
{% endblock body %}
</div>
</section>
<section id="footer">
<div class="body">
{% block footer %}
©2021 Steve Kossouho, <strong>Dawan</strong>
{% endblock footer %}
</div>
</section>
</body>
</html>

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Forms demonstration</title>
</head>
<body>
<h1>Sections of form rendering</h1>
<ul>
<li><a href="{% url "search" %}">Search form</a></li>
<li><a href="{% url "person" %}">Person fields form</a></li>
<li><a href="{% url "upload" %}">Upload form</a></li>
</ul>
</body>
</html>

View File

@ -0,0 +1,15 @@
{% extends "demonstration/base.html" %}
{% block body %}
<form action="" method="post" name="person-form">
{% csrf_token %}
<table class="form-table">
{{ form.as_table }}
<tr>
<th></th>
<td><input type="submit" name="submit-form" value="Validate"></td>
</tr>
</table>
</form>
<hr>
{% endblock body %}

View File

@ -0,0 +1,22 @@
{% extends "demonstration/base.html" %}
{% block body %}
<form action="" method="get" name="search-form">
<table class="form-table">
{{ form.as_table }}
<tr>
<th></th>
<td><input type="submit" name="submit-form" value="Search"></td>
</tr>
</table>
</form>
<hr>
<em>{{ results|length }} results.</em>
<ul>
{% for item in results %}
<li>{{ item }}</li>
{% empty %}
<li>No item found.</li>
{% endfor %}
</ul>
{% endblock body %}

View File

@ -0,0 +1,21 @@
{% extends "demonstration/base.html" %}
{% block body %}
<form action="" method="post" name="upload-form" enctype="multipart/form-data">
{% csrf_token %}
<table class="form-table">
{{ form.as_table }}
<tr>
<th></th>
<td><input type="submit" name="submit-form" value="Upload file"></td>
</tr>
</table>
</form>
<hr>
{% if image_url %}
The image was successfully uploaded at <a href="{{ image_url }}">{{ image_url }}</a>
<p>
<img src="{{ image_url }}" alt="Uploaded image">
</p>
{% endif %}
{% endblock body %}

View File

@ -0,0 +1,9 @@
from django.urls import path
from demonstration.views import view_search_form, view_person_form, view_upload_form
urlpatterns = [
path("search/", view_search_form, name="search"),
path("person/", view_person_form, name="person"),
path("upload/", view_upload_form, name="upload"),
]

View File

@ -0,0 +1,81 @@
from typing import List, Optional
from annoying.decorators import render_to
from django.http import HttpRequest, HttpResponseRedirect
from demonstration.forms import SearchForm, PersonForm, UploadForm
NAMES: List[str] = [
"Jean",
"Paul",
"Robert",
"Julien",
"Nicolas",
"François",
"Julie",
"Marie",
"Anne",
"Évelyne",
"Jeanne",
"Claire",
]
@render_to("demonstration/index.html")
def view_index(request: HttpRequest): # noqa
return {}
@render_to("demonstration/search_form_view.html")
def view_search_form(request: HttpRequest): # noqa
"""
View for the search form.
Args:
request: HTTP request.
Returns:
Data for rendering the template, as a context dictionary.
"""
form = SearchForm(request.GET) if request.GET else SearchForm()
results: List[str] = []
if form.is_valid():
query: str = form.cleaned_data["query"].lower()
results = [item for item in NAMES if query in item.lower()]
return {"form": form, "results": results}
@render_to("demonstration/person_form_view.html")
def view_person_form(request: HttpRequest): # noqa
"""
View for the person form.
Args:
request: HTTP request.
Returns:
Data for rendering the template, as a context dictionary.
"""
form = PersonForm(request.POST) if request.method == "POST" else PersonForm()
return {"form": form}
@render_to("demonstration/upload_form_view.html")
def view_upload_form(request: HttpRequest): # noqa
"""
View for the upload form.
Args:
request: HTTP request.
Returns:
Data for rendering the template, as a context dictionary.
"""
form = UploadForm(request.POST, request.FILES) if request.method == "POST" else UploadForm()
image_url: Optional[str] = None
if form.is_valid():
image_url = form.save_uploaded_file(request)
return {"form": form, "image_url": image_url}

View File

View File

@ -0,0 +1,16 @@
"""
ASGI config for forms project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'forms.settings')
application = get_asgi_application()

View File

@ -0,0 +1,131 @@
"""
Django settings for forms project.
Generated by 'django-admin startproject' using Django 3.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-fp_2(q#373yxtz=sn7!58+x##q_qan$ef#itrz10qj5=e1@w_0"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"demonstration",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "forms.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "forms.wsgi.application"
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
# "default": {
# "ENGINE": "django.db.backends.sqlite3",
# "NAME": BASE_DIR / "db.sqlite3",
# }
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = "/static/"
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
# Media paths
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"

View File

@ -0,0 +1,25 @@
"""forms URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include
from demonstration.views import view_index
urlpatterns = [
path("demonstration/", include("demonstration.urls")),
path("", view_index, name="index"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

View File

@ -0,0 +1,16 @@
"""
WSGI config for forms project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'forms.settings')
application = get_wsgi_application()

22
source/forms/manage.py Normal file
View File

@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'forms.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

32
source/orm/.idea/ORM.iml generated Normal file
View File

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="FacetManager">
<facet type="django" name="Django">
<configuration>
<option name="rootFolder" value="$MODULE_DIR$" />
<option name="settingsModule" value="orm/settings.py" />
<option name="manageScript" value="manage.py" />
<option name="environment" value="&lt;map/&gt;" />
<option name="doNotUseTestRunner" value="false" />
<option name="trackFilePattern" value="" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
</content>
<orderEntry type="jdk" jdkName="Python 3.13 (beginner)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PackageRequirementsSettings">
<option name="requirementsPath" value="$MODULE_DIR$/../../requirements.pip" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="GOOGLE" />
<option name="myDocStringFormat" value="Google" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Django" />
</component>
</module>

View File

@ -0,0 +1,12 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="GrazieInspection" enabled="false" level="TYPO" enabled_by_default="false" />
<inspection_tool class="LanguageDetectionInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false">
<option name="processCode" value="true" />
<option name="processLiterals" value="true" />
<option name="processComments" value="true" />
</inspection_tool>
</profile>
</component>

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

8
source/orm/.idea/modules.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/orm.iml" filepath="$PROJECT_DIR$/.idea/orm.iml" />
</modules>
</component>
</project>

11
source/orm/.idea/workspace.xml generated Normal file
View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showExcludedFiles" value="false" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">
<property name="settings.editor.selected.configurable" value="configurable.group.tools" />
</component>
</project>

BIN
source/orm/database.sqlite3 Normal file

Binary file not shown.

View File

@ -0,0 +1,63 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "c23b09c8",
"metadata": {},
"source": [
"Default use of **ORM** to get objects of a model."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "c1729427",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<PersonQuerySet [<Person: Hans Gruber (client)>, <Person: Ben Richards (client)>, <Person: Ellen Ripley (client)>, <Person: Jill Valentine (employee)>, <Person: Spike Spiegel (client)>, <Person: Jet Black (client)>, <Person: Mark Kaminsky (client)>, <Person: Lily Aldrin (employee)>]>"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"people = Person.objects.all()\n",
"people"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "20b337f5",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Django Shell-Plus",
"language": "python",
"name": "django_extensions"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.2"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@ -0,0 +1,9 @@
from django.apps import AppConfig
class LibraryConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "library"
default_app_config = "library.LibraryConfig"

View File

@ -0,0 +1,4 @@
from .author import AuthorAdmin
from .book import BookAdmin
from .genre import GenreAdmin
from .person import PersonAdmin

View File

@ -0,0 +1,14 @@
from django.contrib import admin
from library.models import Author
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
"""
Admin for book authors.
"""
list_display = ["id", "uuid", "first_name", "last_name"]
list_per_page = 25

View File

@ -0,0 +1,16 @@
from django.contrib import admin
from library.models import Book
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
"""
Admin for books.
"""
list_display = ["id", "name", "isbn", "genre", "year"]
list_editable = ["year", "genre"]
list_filter = ["genre"]
list_per_page = 25

View File

@ -0,0 +1,14 @@
from django.contrib import admin
from library.models import Genre
@admin.register(Genre)
class GenreAdmin(admin.ModelAdmin):
"""
Admin for book genres.
"""
list_display = ["id", "uuid", "code_name", "name"]
list_per_page = 25

View File

@ -0,0 +1,14 @@
from django.contrib import admin
from library.models import Person
@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
"""
Admin for people.
"""
list_display = ["id", "uuid", "user", "role", "first_name", "last_name"]
list_per_page = 25

Binary file not shown.

View File

@ -0,0 +1 @@
from .person import PersonForm

View File

@ -0,0 +1,15 @@
from django import forms
from library.models import Person
class PersonForm(forms.ModelForm):
"""
Django form for the Person model.
"""
class Meta:
model = Person
exclude = ("user", "uuid") # facultatif
fields = "__all__" # soit "__all__" soit une liste de champs qui seront visibles

Binary file not shown.

View File

@ -0,0 +1,101 @@
# Generated by Django 3.2 on 2021-04-12 14:11
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Author',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uuid', models.UUIDField(db_index=True, default=uuid.uuid4, verbose_name='UUID')),
('first_name', models.CharField(max_length=64, verbose_name='first name')),
('last_name', models.CharField(max_length=64, verbose_name='last name')),
('description', models.TextField(blank=True, verbose_name='description')),
('birth_date', models.DateField(default=datetime.date(2000, 1, 1), verbose_name='birth date')),
('registration_date', models.DateTimeField(auto_now_add=True, verbose_name='registration date')),
],
options={
'verbose_name': 'book author',
'verbose_name_plural': 'book authors',
},
),
migrations.CreateModel(
name='Genre',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uuid', models.UUIDField(db_index=True, default=uuid.uuid4, verbose_name='UUID')),
('code_name', models.CharField(max_length=64, unique=True, verbose_name='code name')),
('name', models.CharField(max_length=64, verbose_name='name')),
('description', models.TextField(blank=True, verbose_name='description')),
('creation_date', models.DateTimeField(auto_now_add=True, verbose_name='creation date')),
],
options={
'verbose_name': 'genre',
'verbose_name_plural': 'genres',
},
),
migrations.CreateModel(
name='Person',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('role', models.PositiveSmallIntegerField(choices=[(0, 'employee'), (1, 'client')], db_index=True, default=0, verbose_name='role')),
('uuid', models.UUIDField(db_index=True, default=uuid.uuid4, verbose_name='UUID')),
('first_name', models.CharField(max_length=64, verbose_name='first name')),
('last_name', models.CharField(max_length=64, verbose_name='last name')),
('birth_date', models.DateField(default=datetime.date(2000, 1, 1), verbose_name='birth date')),
('creation_date', models.DateTimeField(auto_now_add=True, verbose_name='creation date')),
('user', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='person', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'person',
'verbose_name_plural': 'people',
},
),
migrations.CreateModel(
name='Book',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uuid', models.UUIDField(db_index=True, default=uuid.uuid4, verbose_name='UUID')),
('isbn', models.CharField(max_length=64, verbose_name='ISBN')),
('name', models.CharField(max_length=128, verbose_name='name')),
('description', models.TextField(blank=True, verbose_name='description')),
('registration_date', models.DateTimeField(auto_now_add=True, verbose_name='creation date')),
('authors', models.ManyToManyField(related_name='books', to='library.Author', verbose_name='authors')),
('genre', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='books', to='library.genre', verbose_name='genre')),
],
options={
'verbose_name': 'book',
'verbose_name_plural': 'books',
},
),
migrations.CreateModel(
name='Loan',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uuid', models.UUIDField(db_index=True, default=uuid.uuid4, verbose_name='UUID')),
('date', models.DateTimeField(auto_now_add=True, verbose_name='date')),
('expected_return', models.DateTimeField(null=True, verbose_name='expected return date')),
('borrowed', models.NullBooleanField(default=True, verbose_name='borrowed')),
('book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='loans', to='library.book', verbose_name='book')),
('person', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='loans', to='library.person', verbose_name='person')),
],
options={
'verbose_name': 'book loan',
'verbose_name_plural': 'book loans',
'unique_together': {('book', 'borrowed')},
},
),
]

View File

@ -0,0 +1,24 @@
# Generated by Django 3.2 on 2021-04-12 14:58
from django.db import migrations, models
import library.models.book
class Migration(migrations.Migration):
dependencies = [
('library', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='book',
name='year',
field=models.PositiveIntegerField(db_index=True, default=1950, null=True, verbose_name='published'),
),
migrations.AlterField(
model_name='book',
name='isbn',
field=models.CharField(default=library.models.book.generate_isbn, max_length=64, verbose_name='ISBN'),
),
]

View File

@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2021-04-12 22:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('library', '0002_add_book_year'),
]
operations = [
migrations.AddField(
model_name='person',
name='picture',
field=models.ImageField(max_length=256, null=True, upload_to='pictures', verbose_name='picture'),
),
]

View File

@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2021-04-13 17:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('library', '0003_person_picture'),
]
operations = [
migrations.AlterField(
model_name='person',
name='picture',
field=models.ImageField(blank=True, max_length=256, null=True, upload_to='pictures', verbose_name='picture'),
),
]

View File

@ -0,0 +1,5 @@
from .author import Author
from .book import Book
from .genre import Genre
from .loan import Loan
from .person import Person

View File

@ -0,0 +1,28 @@
from datetime import date
from uuid import uuid4
from django.db import models
class Author(models.Model):
"""
Model for book authors.
"""
uuid = models.UUIDField(default=uuid4, db_index=True, verbose_name="UUID")
first_name = models.CharField(max_length=64, blank=False, verbose_name="first name")
last_name = models.CharField(max_length=64, blank=False, verbose_name="last name")
description = models.TextField(blank=True, verbose_name="description")
birth_date = models.DateField(default=date(2000, 1, 1), verbose_name="birth date")
registration_date = models.DateTimeField(auto_now_add=True, verbose_name="registration date")
class Meta:
verbose_name = "book author"
verbose_name_plural = "book authors"
def __str__(self):
return f"{self.get_full_name()} ({self.uuid})"
def get_full_name(self):
return f"{self.first_name} {self.last_name}"

View File

@ -0,0 +1,70 @@
import random
import string
from uuid import uuid4
from django.db import models
from django.utils import timezone
def generate_isbn() -> str:
"""
Generate a random ISBN number.
Returns:
A 13-digit string.
"""
digits = string.digits
return "".join(random.choice(digits) for _ in range(13))
class BookQuerySet(models.QuerySet):
"""
QuerySet class for books.
"""
def available(self) -> models.QuerySet:
"""
Get books available for a loan.
Excludes books with at least a loan whose `borrowed` field is `True`.
Given the constraints, only one loan for a book can have the `borrowed` status
to `True`.
"""
return self.exclude(loans__borrowed=True)
def late_returns(self) -> models.QuerySet:
"""
Get books that should have been returned by now.
"""
now = timezone.now()
return self.filter(loans__expected_return__lt=now, borrowed=True)
class Book(models.Model):
"""
Description of a book.
"""
uuid = models.UUIDField(default=uuid4, db_index=True, verbose_name="UUID")
isbn = models.CharField(max_length=64, default=generate_isbn, blank=False, verbose_name="ISBN")
name = models.CharField(max_length=128, blank=False, verbose_name="name")
description = models.TextField(blank=True, verbose_name="description")
registration_date = models.DateTimeField(auto_now_add=True, verbose_name="creation date")
year = models.PositiveIntegerField(default=1950, null=True, db_index=True, verbose_name="published")
authors = models.ManyToManyField("library.Author", related_name="books", verbose_name="authors")
genre = models.ForeignKey(
"library.Genre", on_delete=models.SET_NULL, null=True, related_name="books", verbose_name="genre"
)
objects = BookQuerySet.as_manager()
class Meta:
verbose_name = "book"
verbose_name_plural = "books"
def __str__(self):
return f"{self.name} ({self.isbn})"

View File

@ -0,0 +1,23 @@
from uuid import uuid4
from django.db import models
class Genre(models.Model):
"""
Book genre.
"""
uuid = models.UUIDField(default=uuid4, db_index=True, verbose_name="UUID")
code_name = models.CharField(max_length=64, blank=False, unique=True, verbose_name="code name")
name = models.CharField(max_length=64, blank=False, verbose_name="name")
description = models.TextField(blank=True, verbose_name="description")
creation_date = models.DateTimeField(auto_now_add=True, verbose_name="creation date")
class Meta:
verbose_name = "genre"
verbose_name_plural = "genres"
def __str__(self):
return f"{self.name}"

View File

@ -0,0 +1,29 @@
from uuid import uuid4
from django.db import models
class Loan(models.Model):
"""
Model for book loans.
"""
uuid = models.UUIDField(default=uuid4, db_index=True, verbose_name="UUID")
person = models.ForeignKey("library.Person", on_delete=models.CASCADE, related_name="loans", verbose_name="person")
book = models.ForeignKey("library.Book", on_delete=models.CASCADE, related_name="loans", verbose_name="book")
date = models.DateTimeField(auto_now_add=True, verbose_name="date")
expected_return = models.DateTimeField(null=True, verbose_name="expected return date")
borrowed = models.BooleanField(null=True, default=True, verbose_name="borrowed")
class Meta:
verbose_name = "book loan"
verbose_name_plural = "book loans"
unique_together = [("book", "borrowed")]
def __str__(self):
return f"Book loan: {self.person}{self.book}"
def return_book(self):
self.borrowed = None
self.save()

View File

@ -0,0 +1,74 @@
from datetime import date, timedelta
from typing import Optional
from uuid import uuid4
from django.db import models, IntegrityError
from django.utils import timezone
import library
class PersonQuerySet(models.QuerySet):
"""
Manager for people.
"""
def employees(self) -> models.QuerySet:
"""Get only employees."""
return self.filter(role=Person.Role.EMPLOYEE)
def clients(self) -> models.QuerySet:
"""Get only clients."""
return self.filter(role=Person.Role.CLIENT)
class Person(models.Model):
"""
Base class for people, employees and clients.
"""
class Role(models.IntegerChoices):
EMPLOYEE = 0, "employee"
CLIENT = 1, "client"
role = models.PositiveSmallIntegerField(default=0, choices=Role.choices, db_index=True, verbose_name="role")
user = models.OneToOneField("auth.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="person")
uuid = models.UUIDField(default=uuid4, db_index=True, verbose_name="UUID")
first_name = models.CharField(max_length=64, blank=False, verbose_name="first name")
last_name = models.CharField(max_length=64, blank=False, verbose_name="last name")
birth_date = models.DateField(default=date(2000, 1, 1), verbose_name="birth date")
creation_date = models.DateTimeField(auto_now_add=True, verbose_name="creation date")
picture = models.ImageField(max_length=256, null=True, blank=True, upload_to="pictures", verbose_name="picture")
objects = PersonQuerySet.as_manager()
class Meta:
verbose_name = "person"
verbose_name_plural = "people"
def __str__(self):
return f"{self.get_full_name()} ({self.get_role_display()})"
def get_full_name(self):
return f"{self.first_name} {self.last_name}"
def borrow(self, book: "library.models.Book", duration: int = 7) -> Optional["library.models.Loan"]:
"""
Borrow a book.
Args:
book: book instance to borrow
duration: expected duration of loan in days
Returns:
If the book can be borrowed, return the new `Loan` object.
If not, return `None`.
"""
try:
deadline = timezone.now() + timedelta(days=duration)
loan = self.loans.create(person=self, book=book, expected_return=deadline)
return loan
except IntegrityError:
return None

Some files were not shown because too many files have changed in this diff Show More