How to implement registration and login functionality in Django?

To implement Django registration and login functionality, you can refer to the following steps:

  1. To create a Django project: Begin by creating a Django project, which can be done by running the command django-admin startproject myproject to create a project named myproject.
  2. Create an application: go to the project directory and run the command “python manage.py startapp accounts” to create an application called accounts.
  3. Configure the application: add the ‘accounts’ application to the INSTALLED_APPS list in the settings.py file.
  4. Create a user model: Define a user model in the models.py file, you can extend the default user model by using AbstractUser.
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    # 添加自定义字段
    pass
  1. To transfer the database: run the commands python manage.py makemigrations and python manage.py migrate to migrate the database and create the table corresponding to the user model.
  2. Create a registration view: Create a registration view in the views.py file that handles the user registration logic.
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from .forms import SignUpForm

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            user = authenticate(request, username=username, password=password)
            login(request, user)
            return redirect('home')
    else:
        form = SignUpForm()
    return render(request, 'signup.html', {'form': form})
  1. forms.py can be rephrased as “forms file”.
from django import forms
from .models import User

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

    class Meta:
        model = User
        fields = ('username', 'password', 'email')
  1. The views.py file
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from .forms import LoginForm

def signin(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(request, username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect('home')
    else:
        form = LoginForm()
    return render(request, 'signin.html', {'form': form})
  1. The file named forms.py
from django import forms

class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)
  1. Python file containing URL patterns
from django.urls import path
from . import views

urlpatterns = [
    path('signup/', views.signup, name='signup'),
    path('signin/', views.signin, name='signin'),
]
  1. Create templates: Create templates for registration and login, corresponding to the files signup.html and signin.html respectively.
  2. Run the project: Use the command “python manage.py runserver” to start the Django development server, then access the registration and login pages to test.

The steps outlined above are a basic implementation of Django registration and login functionality, which can be further expanded and optimized according to specific needs.

bannerAds