How do I write a try and except code for a password validation; such that each validation returns its own message to the user?

Question:

views.py

The issue I have is on the signup function view.
What do I write inside the except block to show an error message to the user according to the validationError given.

for example: if the error is "Common Password" it should only display common password message to the user and if it is other errors, it should do the same for their independent messages to the user.

from django.shortcuts import render,redirect
from  django.contrib import messages
from django.contrib.auth import authenticate,login,logout
#from django.contrib.auth.models import User
from django.core.mail import send_mail
from .models import User 
from django.contrib.auth.password_validation import validate_password,UserAttributeSimilarityValidator,CommonPasswordValidator,MinimumLengthValidator,NumericPasswordValidator

# Create your views here.

def signup(request):

    if request.method == "POST":
        username = request.POST.get("username")
        fname = request.POST.get("fname")
        lname = request.POST.get("lname")
        email = request.POST.get("email")
        password = request.POST.get("password")
        password2 = request.POST.get("password2")



        if password:
            try:
                new = validate_password(password,password_validators=None)
                
            except:
                messages.error(request, )
                return redirect('home')


    






        




                
        #if User.objects.filter(email=email):
            #messages.error(request, "E-mail already exist!")
            #return redirect('home')

        #if len(username) > 15:
            #messages.error(request, "Length of username too long!")
            #return redirect('home')

        #if password != password2:
            #messages.error(request, "Passwords do not match!")
            #return redirect('home')

        #if not password.isalnum():
            #messages.error(request, "Password must be alphanumeric!")
            #return redirect('home')
          

        user = User.objects.create_user(username=username,first_name=fname,last_name=lname,email=email,password=password)


        # Welcome E-mail

        #subject = 'Welcome to ADi meals mobile!'
        #message = 'Hello {fname}, welcome to ADi meals mobile!nThank you for visiting our website.n We have also sent you a confirmation email, please confirm your email address to login into your account.nnThanking younVictoria OluwaseyinC.E.O'
        #from_email = settings.EMAIL_HOST_USER
        #to_list = [user.email]
        #send_mail(subject,message,from_email,to_list,fail_silently=True)


        messages.success(request,"Your account has been successfully created!")
        #user.is_active = True
        return redirect('authentication:signin')

         
    return render(request,'authentication/signup.html')

Answers:

You could create another function, where you pass the username, email and password to, in which you process them and return a string value, which you can give as a message in the return of your original function.

Example:

def checkFields(user, email, pwd, pwd2):

        #if User.objects.filter(email=email):
            #message = "email already exists"
            #return message

        #if len(user) > 15:
            #message = "Length of username is too long"
            #return message

        #if pwd != pwd2:
            #message = "Passwords do not match"
            #return message

        #if not pwd.isalnum():
            #message = "Password must be alphanumeric"
        
        #return message

def signup(request):

    if request.method == "POST":
        username = request.POST.get("username")
        fname = request.POST.get("fname")
        lname = request.POST.get("lname")
        email = request.POST.get("email")
        password = request.POST.get("password")
        password2 = request.POST.get("password2")

        custom_message = checkFields(username, email, password, password2)

        if password:
            try:
                new = validate_password(password,password_validators=None)
                
            except:
                if custom_message != None:
                    messages.error(request, custom_message)
                else: 
                    messages.error(request, 'somethign went wrong')
                return redirect('home')

            #
            #The rest of your code here....
            #
Answered By: Tim-Bolhoeve

Here is exactly what I did. To validate each password input and return a one word message on each validation, make use of try and except block, and you can even add a passwordchange function to ensure that a user does not use the old password while changing password.

def setpassword(request):
    new = ""
    username = request.user.username
    if request.method == "POST":
        password = request.POST.get("password")
        password2 = request.POST.get("password2")

        user = User.objects.get(username=username)
    
        if password:

            if password != password2:
                messages.error(request,"Passwords do not match!")
                return redirect('authentication:setpassword')
                
            try:
                UserAttributeSimilarityValidator().validate(password)
                try:
                    password_changed(password,user=User,password_validators=UserAttributeSimilarityValidator)
                except:
                    messages.error(request, "Old password cannot be used!nPlease, try a new password.")
                    return redirect('authentication:setpassword')
            except:
                messages.error(request,"Password too similar to user attribute provided.nPlease, try another password!")
                return redirect('authentication:setpassword')
            try:
                CommonPasswordValidator().validate(password)
                try:
                    password_changed(password,user=User,password_validators=CommonPasswordValidator)
                except:
                    messages.error(request, "Old password cannot be used!nPlease, try a new password.")
                    return redirect('authentication:setpassword')
            except:
                messages.error(request,"Password too common and easy.nPlease, try another password!")
                return redirect('authentication:setpassword')
            try:
                MinimumLengthValidator().validate(password)
                try:
                    password_changed(password,user=User,password_validators=MinimumLengthValidator)
                except:
                    messages.error(request, "Old password cannot be used!nPlease, try a new password.")
                    return redirect('authentication:setpassword')
            except:
                messages.error(request,"Only a minimum characters of 8 is allowed.nPlease, try another password!")
                return redirect('authentication:setpassword')
            try:
                NumericPasswordValidator().validate(password)
                try:
                    password_changed(password,user=User,password_validators=NumericPasswordValidator)
                except:
                    messages.error(request, "Old password cannot be used!nPlease, try a new password.")
                    return redirect('authentication:setpassword')
            except:
                messages.error(request,"Numeric only password is not allowed.nPlease, try another password!")
                return redirect('authentication:setpassword')


            user.set_password(password)
            user.save()
            messages.success(request, "You have successfully changed your password!")
            return redirect('authentication:signin')

    return render(request,'authentication/setpassword.html')
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.