Code-Memo

User Registration

Handling user registration involves creating a new user, validating input data, and securely storing the password.

Creating a User

The User model provides a method for creating new users with hashed passwords.

from django.contrib.auth.models import User

user = User.objects.create_user(username='john', password='securepassword', email='john@example.com')
user.save()

Using Forms for User Registration

A ModelForm simplifies user registration by handling validation automatically.

from django import forms
from django.contrib.auth.models import User

class RegistrationForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ['username', 'email', 'password']

Handling Registration in a View

A view processes the registration form and creates a new user if the input is valid.

from django.shortcuts import render, redirect
from django.contrib.auth import login
from .forms import RegistrationForm

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.set_password(form.cleaned_data['password'])
            user.save()
            login(request, user)
            return redirect('dashboard')
    else:
        form = RegistrationForm()
    return render(request, 'register.html', {'form': form})

Registration Template

A simple template collects user details and submits the form.

<form method="post">
    &#123;% endraw %&#125;&#123;% csrf_token %&#125;
    
    <button type="submit">Register</button>
</form>

Redirecting After Registration

After successful registration, users can be redirected to a dashboard or login page.

return redirect('dashboard')  # Redirects to the user's dashboard