Registrazione Utenti
La registrazione degli utenti e una funzionalita essenziale per la maggior parte delle applicazioni web. Django fornisce UserCreationForm come punto di partenza e permette di estenderlo facilmente per raccogliere informazioni aggiuntive.
UserCreationForm Base
Django include un form pronto per la registrazione che gestisce username e password:
# views.py
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
def registrazione(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = UserCreationForm()
return render(request, 'registration/registrazione.html', {'form': form})
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('registrazione/', views.registrazione, name='registrazione'),
]
Il template per la registrazione:
# templates/registration/registrazione.html
# {% extends "base.html" %}
#
# {% block content %}
# <h2>Crea un Account</h2>
# <form method="post">
# {% csrf_token %}
# {{ form.as_p }}
# <button type="submit">Registrati</button>
# </form>
# <p>Hai gia un account? <a href="{% url 'login' %}">Accedi</a></p>
# {% endblock %}
Form di Registrazione Personalizzato
Il UserCreationForm base include solo username e password. Per aggiungere campi come email, nome e cognome, crea un form personalizzato:
# forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class RegistrazioneForm(UserCreationForm):
email = forms.EmailField(
required=True,
label="Indirizzo Email",
widget=forms.EmailInput(attrs={'class': 'form-control'})
)
first_name = forms.CharField(
max_length=50,
required=True,
label="Nome",
widget=forms.TextInput(attrs={'class': 'form-control'})
)
last_name = forms.CharField(
max_length=50,
required=True,
label="Cognome",
widget=forms.TextInput(attrs={'class': 'form-control'})
)
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2']
def clean_email(self):
email = self.cleaned_data.get('email')
if User.objects.filter(email=email).exists():
raise forms.ValidationError("Questa email e gia registrata.")
return email
Registrazione con Login Automatico
Puoi autenticare automaticamente lâutente subito dopo la registrazione:
from django.contrib.auth import login
from .forms import RegistrazioneForm
def registrazione(request):
if request.method == 'POST':
form = RegistrazioneForm(request.POST)
if form.is_valid():
utente = form.save()
login(request, utente)
return redirect('dashboard')
else:
form = RegistrazioneForm()
return render(request, 'registration/registrazione.html', {'form': form})
Registrazione con Class-Based View
Puoi usare CreateView per una vista di registrazione basata su classi:
from django.views.generic.edit import CreateView
from django.contrib.auth import login
from django.urls import reverse_lazy
from .forms import RegistrazioneForm
class RegistrazioneView(CreateView):
form_class = RegistrazioneForm
template_name = 'registration/registrazione.html'
success_url = reverse_lazy('dashboard')
def form_valid(self, form):
response = super().form_valid(form)
login(self.request, self.object)
return response
Registrazione con Profilo Aggiuntivo
Se hai un modello profilo collegato allâutente, puoi crearlo durante la registrazione:
# models.py
from django.db import models
from django.contrib.auth.models import User
class Profilo(models.Model):
utente = models.OneToOneField(User, on_delete=models.CASCADE)
telefono = models.CharField(max_length=20, blank=True)
data_nascita = models.DateField(null=True, blank=True)
citta = models.CharField(max_length=100, blank=True)
# views.py
from .models import Profilo
def registrazione(request):
if request.method == 'POST':
form = RegistrazioneForm(request.POST)
if form.is_valid():
utente = form.save()
Profilo.objects.create(utente=utente)
login(request, utente)
return redirect('completa_profilo')
else:
form = RegistrazioneForm()
return render(request, 'registration/registrazione.html', {'form': form})
Concetti di Verifica Email
Per la verifica email, il flusso tipico prevede la generazione di un token univoco e lâinvio di un link di conferma:
from django.contrib.auth.tokens import default_token_generator
from django.utils.http import urlsafe_base64_encode
from django.utils.encoding import force_bytes
from django.core.mail import send_mail
def invia_email_verifica(utente, request):
token = default_token_generator.make_token(utente)
uid = urlsafe_base64_encode(force_bytes(utente.pk))
link = f"{request.scheme}://{request.get_host()}/verifica/{uid}/{token}/"
send_mail(
'Verifica il tuo account',
f'Clicca sul link per verificare il tuo account: {link}',
'noreply@esempio.it',
[utente.email],
)
from django.utils.http import urlsafe_base64_decode
from django.contrib.auth import get_user_model
def verifica_email(request, uidb64, token):
User = get_user_model()
try:
uid = urlsafe_base64_decode(uidb64).decode()
utente = User.objects.get(pk=uid)
except (TypeError, ValueError, User.DoesNotExist):
utente = None
if utente and default_token_generator.check_token(utente, token):
utente.is_active = True
utente.save()
return redirect('login')
else:
return render(request, 'verifica_fallita.html')
Conclusione
Django offre tutti gli strumenti necessari per implementare un sistema di registrazione completo. Partendo da UserCreationForm, puoi estendere il form con campi personalizzati, aggiungere il login automatico dopo la registrazione, creare profili aggiuntivi e implementare la verifica email. La chiave e scegliere il livello di complessita adeguato alle esigenze del tuo progetto.