Django
Django Ă© un framework in Python con lâobiettivo di creare unâapplicazione in tempi relativamente brevi.
Ă modulare, quindi aggiungere e rimuovere funzionalitĂĄ Ă© veramente semplice.
Start a new project
django-admin startproject mysiteLetâs look at what startproject created:
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
These files are:
- The outer
mysite/root directory is a container for your project. manage.py: A command-line utility that lets you interact with this Django project in various ways. You can read all the details aboutmanage.pyin django-admin and manage.py.- The inner
mysite/directory is the actual Python package for your project. Its name is the Python package name youâll need to use to import anything inside it (e.g.mysite.urls). mysite/__init__.py: An empty file that tells Python that this directory should be considered a Python package. If youâre a Python beginner, read more about packages in the official Python docs.mysite/settings.py: Settings/configuration for this Django project. Django settings will tell you all about how settings work.mysite/urls.py: The URL declarations for this Django project; a âtable of contentsâ of your Django-powered site. You can read more about URLs in URL dispatcher.mysite/asgi.py: An entry-point for ASGI-compatible web servers to serve your project. See How to deploy with ASGI for more details.mysite/wsgi.py: An entry-point for WSGI-compatible web servers to serve your project. See How to deploy with WSGI for more details.
Far partire il server
python manage.py runserver server:porta
Ogni volta bisogna creare un app, poichĂ© allâinterno di un progetto possono esserci piĂč app.
python manage.py startapp nomeapp
Dentro app:
- nelle view definisci cosa deve ritornare il server
- si crea un file chiamato urls.py che Ăš il router
Dentro invece la cartella del progetto si definisce urls.py (non devo crearlo) che utilizza lâapp di prima.
Bisogna poi:
- configurare le impostazioni del db su
progetto/settings.py - container Docker con postgres installato e funzionante
- questo Ăš un comodo Dockerfile:
version: '3.8'
services:
db:
image: postgres:14.1-alpine
restart: always
environment:
- POSTGRES_DB=.
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=docker
ports:
- '5432:5432'
volumes:
- db:/var/lib/postgresql/data
volumes:
db:
driver: local
Migrazioni
Ogni volta che si effettua un cambiamento allo schema del db bisogna rifare le migrazioni.
Le migrazioni sono come Django traduce le app installate in tabelle del database.
Quindi, prima si fanno le migrazioni dellâapp creata:
python manage.py makemigrations polls
e poi
python manage.py migrate
Vedere SQL eseguito e controllare migrazioni
python manage.py sqlmigrate nomeapp numero
Controllare:
python manage.py check
Modelli
I modelli servono per definire a tutti gli effetti le entitĂ del database.
Vanno definit allâinterno di models.py, si usa un approccio a classi e vanno usati campi specifici di Django.
Un piccolo esempio:
from django.db import models
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)Quasi sempre va definito il metodo __str__ altrimenti in fase di debug ci ritroviamo una rappresentazione inutile.
Superadmin
Creating an admin user
First weâll need to create a user who can login to the admin site. Run the following command:
$ python manage.py createsuperuser
Enter your desired username and press enter.
Username: admin
You will then be prompted for your desired email address:
Email address: admin@example.com
The final step is to enter your password. You will be asked to enter your password twice, the second time as a confirmation of the first.
Password: **********
Password (again): *********
Superuser created successfully.
Ok, ma lâapp non câĂš.
Devo registrare che esiste nella parte admin.py di nomeapp, quindi vado lĂŹ:
from .models import Question
admin.site.register(Question)Runnare i test
python manage.py test
Sono contenuto allâinterno del file tests.py o al limite in ogni sottocartella.
FAQ
-
Mentre si definisce un modello, qual Ăš la differenza tra
null=Trueeblank=True?null=True: nel database puo avere campo null, ma non in un form di inserimentoblank=True: lo marca come non obbligatorio, ad esempio in un form
-
Come effettuo un aggiornamento di unâapplicazione Django? Come faccio ad aggiornare unâapplicazione Django paleolitico al giorno dâoggi?
- nel progetto, installa con pip
django-upgradee runnagit ls-files -- '*.py' | xargs django-upgrade --target-version 4.2 - dovrai comunque metterci le mani, in quanto non riuscirĂ a fare tutto il lavoro per te
- nel progetto, installa con pip
DjangoFAQ
This is a test.
Link all'originale