1 Introduzione a django

Introduzione allo sviluppo per Django. Il work flow di una applicazione web MVC: Modello, Controller, View.

Author:

eaman

Copyright:

GFDL

Version:

0.1

Questi appunti sono ad uso privato.

Generato il 2024-01-27 con: http://docutils.sourceforge.net/rst.html

1.1 Create project

mkdir project_name
django-admin startproject name .
python manage.py startapp
./mange.py createsuperuser

mkdir templates static

1.1.1 Settings

top environ:

import os
# Enviroment stuff
from environs import Env
env = Env()
env.read_env()


#DEBUG = True
DEBUG = env.bool("DEBUG", default=False)

# Secret_key: gen with python -c 'import secrets; print(secrets.token_urlsafe())'
# and put in .env
SECRET_KEY = env.str("SECRET_KEY")

1.1.1.1 settings.py regionals::

TIME_ZONE = 'Europe/Rome'

LANGUAGE_CODE = 'it'

Register app:

INSTALLED_APPS = [
...
    'my_app_name',
    ]

settings.py:

import os
...

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [

            os.path.join(BASE_DIR, 'templates'),
      ...
    },

1.1.1.2 Static files::

settings.py:

STATIC_URL = 'static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles')) # new
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'

Launch:

./manage.py collectstatic

virtual host:

Alias /robots.txt /path/to/mysite.com/static/robots.txt
Alias /favicon.ico /path/to/mysite.com/static/favicon.ico

Alias /media/ /path/to/mysite.com/media/
Alias /static/ /path/to/mysite.com/static/

<Directory /path/to/mysite.com/static>
    Require all granted
</Directory>

<Directory /path/to/mysite.com/media>
    Require all granted
</Directory>

WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py

<Directory /path/to/mysite.com/mysite>
<Files wsgi.py>
    Require all granted
</Files>
</Directory>

1.2 Change apps templates

Files are located in:

env/lib/python3.10/site-packages/django/conf/app_template/

env/lib/python3.10/site-packages/django/conf/project_template/

Add / change modify content there

1.3 Crispyform

settings.py:

INSTALLED_APPS = [

    'crispy_forms',
    "crispy_bootstrap5",

    ]
...
# End

CRISPY_TEMPLATE_PACK = 'bootstrap5'

1.4 Auth

settings.py:

INSTALLED_APPS = [
...

'users',
]

#########
# Auth stuff
AUTH_USER_MODEL = "users.CustomUser"
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'

1.4.1 Model

Inside users app:

models.py:

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


class CustomUser(AbstractUser):
    age = models.PositiveIntegerField(null=True, blank=True)

forms.py:

# users/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser

class CustomUserCreationForm(UserCreationForm):

    class Meta(UserCreationForm.Meta):
        model = CustomUser
        # This is bad, better to just list the field like in the next
        fields = UserCreationForm.Meta.fields + ('age', 'email')


class CustomUserChangeForm(UserChangeForm):

    class Meta:
        model = CustomUser
        fields = ('username', 'email', 'age',)

admin.py:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm

from .models import CustomUser

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['age', 'username', 'email', 'is_staff', ]

    add_fieldsets = UserAdmin.add_fieldsets + ( # new
        (None, {'fields': ('age',)}),
    )



admin.site.register(CustomUser, CustomUserAdmin)

1.4.2 Templates

There are a lot of templates to make! Just check the main example repo.

1.5 Models

  • Modello base

  • Relazione 1-M

  • slug

1.6 Views

urls.py:

from django.urls import path
from . import views
from news.views import *

from news.models import *

urlpatterns = [
    path('', views.index, name='index'),
    path('publishers/', PublisherListView.as_view()),
    path('publishers/<int:pk>/', PublisherDetailView.as_view()),
]

1.6.1 Views

from django.views.generic import ListView, DetailView
from news.models import Publisher


# Create your views here.
class PublisherListView(ListView):
    model = Publisher


class PublisherDetailView(DetailView):
    model = Publisher

1.6.2 Detail View

1.7 Static website

Generate a static version:

wget -k -K  -E -r -l 10 -p -N -F --restrict-file-names=windows -nH http://127.0.0.1:8000/

1.8 Deployment

1.8.1 Gunicorn

Se si ha un progetto ‘’sito’’ che contiene ‘’sito_config’’ con dentro ‘’wsgi.py’’:

gunicorn newspaper_project.wsgi


gunicorn newspaper_project.wsgi -b 0.0.0.0:8082
gunicorn newspaper_project.wsgi -b 0.0.0.0:8082 --daemon

1.8.2 Whitenoise

settings.py:

MIDDLEWARE = [
    # ...
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    # ...
]

Per servire solo l’Admin non serve fare la parte ‘’static’’:

mkdir static
./manage.py collectstatic

1.8.3 Lighthttpd proxy

/etc/lighttpd/lighttpd.conf

#######
# Gunicorn django proxy
$HTTP["host"] == "home.chrome" {
  proxy.balance = "hash"
  proxy.server = ( "" => ( (
        "host" => "127.0.0.1",
        "port" => 8081
    ) ) )
}

script:

gunicorn newspaper_project.wsgi -b 0.0.0.0:8081 --daemon

I ‘’settings’’ sono sopra.