Python Django Login register
Step 1: Install Django
pip install django
Step 2: Create a Django project
django-admin startproject myproject
Step 3: Create a Django app
cd myproject
python manage.py startapp myapp
Step 4: Define models in myapp/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
# Add custom fields if needed
pass
Step 5: Configure the custom user model in myproject/settings.py
AUTH_USER_MODEL = 'myapp.CustomUser'
Step 6: Create and apply migrations
python manage.py makemigrations
python manage.py migrate
Step 7: Create forms in myapp/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = CustomUser
fields = ('username', 'email')
Step 8: Create views in myapp/views.py
from django.shortcuts import render, redirect
from django.contrib.auth import login
from .forms import CustomUserCreationForm
def register(request):
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect('home') # Replace 'home' with your home URL
else:
form = CustomUserCreationForm()
return render(request, 'registration/register.html', {'form': form})
Step 9: Create templates in myapp/templates/registration/register.html
{% extends 'base.html' %}
{% block content %}
<h2>Register</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
{% endblock %}
Step 10: Configure URLs in myapp/urls.py
from django.urls import path
from .views import register
urlpatterns = [
path('register/', register, name='register'),
# Add more URLs as needed
]
Step 11: Include app URLs in myproject/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('myapp.urls')),
# Add more URLs as needed
]
Step 12: Create a superuser
python manage.py createsuperuser
Step 13: Run the development server
python manage.py runserver
Visit http://localhost:8000/admin/
to log in with the superuser credentials and manage users. Visit http://localhost:8000/accounts/register/
to access the registration page.