Django Sign Up and login with confirmation Email | Python

25 May, 2022
Django by default provides an authentication system configuration. User objects are the core of the authentication system.today we will implement Django’s authentication system. 
Modules required : 
django : django install
crispy_forms :
pip install --upgrade django-crispy-forms
Basic setup :Start a project by the following command –
 django-admin startproject project
Change directory to project –
 cd project
Start the server- Start the server by typing the following command in terminal –
 python manage.py runserver
To check whether the server is running or not go to a web browser and enter http://127.0.0.1:8000/ as URL.Now stop the server by pressing
ctrl-c
Let’s create an app now called the “user”. 
python manage.py startapp user
Goto user/ folder by doing: cd user and create a folder templates with files index.html, login.html, Email.html, register.html files. 
Open the project folder using a text editor. The directory structure should look like this : 
Now add the “user” app and “crispy_form” in your todo_site in settings.py, and add 
CRISPY_TEMPLATE_PACK = 'bootstrap4'
at last of settings.py  
configure email settings in setting.py: 
place your email and password here. 
Edit urls.py file in project :  
Python3
from django.contrib import adminfrom django.urls import path, includefrom user import views as user_viewfrom django.contrib.auth import views as auth  urlpatterns = [      path('admin/', admin.site.urls),      ##### user related path##########################     path('', include('user.urls')),    path('login/', user_view.Login, name ='login'),    path('logout/', auth.LogoutView.as_view(template_name ='user/index.html'), name ='logout'),    path('register/', user_view.register, name ='register'),  ]
Edit urls.py in user : 
Python3
from django.urls import path, includefrom django.conf import settingsfrom . import viewsfrom django.conf.urls.static import static  urlpatterns = [         path('', views.index, name ='index'),]
Edit views.py in user :
Python3
from django.shortcuts import render, redirectfrom django.contrib import messagesfrom django.contrib.auth import authenticate, loginfrom django.contrib.auth.decorators import login_requiredfrom django.contrib.auth.forms import AuthenticationFormfrom .forms import UserRegisterFormfrom django.core.mail import send_mailfrom django.core.mail import EmailMultiAlternativesfrom django.template.loader import get_templatefrom django.template import Context      #################### index####################################### def index(request):    return render(request, 'user/index.html', {'title':'index'})   ########### register here ##################################### def register(request):    if request.method == 'POST':        form = UserRegisterForm(request.POST)        if form.is_valid():            form.save()            username = form.cleaned_data.get('username')            email = form.cleaned_data.get('email')            ######################### mail system ####################################             htmly = get_template('user/Email.html')            d = { 'username': username }            subject, from_email, to = 'welcome', 'your_email@gmail.com', email            html_content = htmly.render(d)            msg = EmailMultiAlternatives(subject, html_content, from_email, [to])            msg.attach_alternative(html_content, "text/html")            msg.send()            ##################################################################             messages.success(request, f'Your account has been created ! You are now able to log in')            return redirect('login')    else:        form = UserRegisterForm()    return render(request, 'user/register.html', {'form': form, 'title':'reqister here'})   ################ login forms################################################### def Login(request):    if request.method == 'POST':           # AuthenticationForm_can_also_be_used__           username = request.POST['username']        password = request.POST['password']        user = authenticate(request, username = username, password = password)        if user is not None:            form = login(request, user)            messages.success(request, f' wecome {username} !!')            return redirect('index')        else:            messages.info(request, f'account done not exit plz sign in')    form = AuthenticationForm()    return render(request, 'user/login.html', {'form':form, 'title':'log in'})
Configure your email here. 
Now create a forms.py in user :
Python3
from django import formsfrom django.contrib.auth.models import Userfrom django.contrib.auth.forms import UserCreationForm      class UserRegisterForm(UserCreationForm):    email = forms.EmailField()    phone_no = forms.CharField(max_length = 20)    first_name = forms.CharField(max_length = 20)    last_name = forms.CharField(max_length = 20)    class Meta:        model = User        fields = ['username', 'email', 'phone_no', 'password1', 'password2']
Navigate to templates/user/ and edit files : 
link to index.html file
link to Email.html
link to login.html
link to register.html
Make migrations and migrate them. 
python manage.py makemigrations
python manage.py migrate
Now you can run the server to see your app.
python manage.py runserver
 
 
udit5656
Django-Projects
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.