0% found this document useful (0 votes)
8 views6 pages

Exp15 Yash

This document outlines the steps to create a user authentication system using Django, including setting up a project, creating a user registration form, and implementing login functionality. It includes regex validations for username, email, and password, as well as views for handling user registration and login. Additionally, it provides HTML templates for the registration and login forms, and configures URL routing for the accounts app.

Uploaded by

yash.pandey1403
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views6 pages

Exp15 Yash

This document outlines the steps to create a user authentication system using Django, including setting up a project, creating a user registration form, and implementing login functionality. It includes regex validations for username, email, and password, as well as views for handling user registration and login. Additionally, it provides HTML templates for the registration and login forms, and configures URL routing for the accounts app.

Uploaded by

yash.pandey1403
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

pip install Django

django-admin startproject user_auth

cd user_auth

python manage.py startapp accounts

from django import forms

from django.core.exceptions import ValidationError

import re

from django.contrib.auth.models import User

username_regex = re.compile(r'^[a-zA-Z0-9]*$') # Alphanumeric username

email_regex = re.compile(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')

password_regex = re.compile(r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*?&]{8,}$') # Password


should be at least 8 chars, contain a number, and a letter.

class UserRegistrationForm(forms.ModelForm):

password = forms.CharField(widget=forms.PasswordInput)

confirm_password = forms.CharField(widget=forms.PasswordInput)

class Meta:

model = User

fields = ['username', 'email', 'password']

def clean_username(self):

username = self.cleaned_data['username']

if not username_regex.match(username):

raise ValidationError('Username should be alphanumeric.')

if User.objects.filter(username=username).exists():

raise ValidationError('Username already exists.')

return username

def clean_email(self):

email = self.cleaned_data['email']
if not email_regex.match(email):

raise ValidationError('Enter a valid email address.')

if User.objects.filter(email=email).exists():

raise ValidationError('Email is already registered.')

return email

def clean_password(self):

password = self.cleaned_data['password']

if not password_regex.match(password):

raise ValidationError('Password must be at least 8 characters long, and contain at least


one letter and one number.')

return password

def clean_confirm_password(self):

password = self.cleaned_data['password']

confirm_password = self.cleaned_data['confirm_password']

if password != confirm_password:

raise ValidationError('Passwords do not match.')

return confirm_password

class UserLoginForm(forms.Form):

username = forms.CharField(max_length=150)

password = forms.CharField(widget=forms.PasswordInput)

from django.shortcuts import render, redirect

from django.contrib.auth import authenticate, login

from django.contrib.auth.forms import AuthenticationForm

from django.contrib import messages

from .forms import UserRegistrationForm, UserLoginForm

def register(request):

if request.method == 'POST':
form = UserRegistrationForm(request.POST)

if form.is_valid():

user = form.save(commit=False)

user.set_password(form.cleaned_data['password']) # Hash the password

user.save()

messages.success(request, 'Registration successful! You can now log in.')

return redirect('login')

else:

messages.error(request, 'Please correct the errors below.')

else:

form = UserRegistrationForm()

return render(request, 'accounts/register.html', {'form': form})

def user_login(request):

if request.method == 'POST':

form = UserLoginForm(request.POST)

if form.is_valid():

username = form.cleaned_data['username']

password = form.cleaned_data['password']

user = authenticate(request, username=username, password=password)

if user is not None:

login(request, user)

messages.success(request, f'Welcome, {user.username}!')

return redirect('home') # Redirect to a home page after login

else:

messages.error(request, 'Invalid username or password.')

else:

form = UserLoginForm()

return render(request, 'accounts/login.html', {'form': form})

from django.urls import path

from . import views


urlpatterns = [

path('register/', views.register, name='register'),

path('login/', views.user_login, name='login'),

] from django.contrib import admin

from django.urls import path, include

urlpatterns = [

path('admin/', admin.site.urls),

path('accounts/', include('accounts.urls')),

] <!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Register</title>

</head>

<body>

<h2>Register</h2>

<form method="POST">

{% csrf_token %}

{{ form.as_p }}

<button type="submit">Register</button>

</form>

<p>Already have an account? <a href="{% url 'login' %}">Login</a></p>

</body>

</html>
INSTALLED_APPS = [

# Other apps...

'accounts',

] MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'python
manage.py runserver

from django.contrib import admin

from django.contrib.auth.models import User

admin.site.register(User) Login
[suleimanpatel] |

[suleiman@example.com] |

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy