Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Adding password validations in a ModelForm

I have made a ModelForm in Django for the registration of a new user. It has 4 fields (username, email, password, and confirm_password). I want to add some validations for the password field. For example, if the password is shorter than 8 characters or the password is similar to the username, then raise an error message. How can I do this?

Here is my forms.py file:

from django.contrib.auth.models import User
from django import forms

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

    class Meta:
        model = User
        fields = ['username','email', 'password','confirm_password']

My settings.py already contains the following validators:

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimila‌​rityValidator', 
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValida‌​tor',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValid‌​ator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordVali‌​dator',
    }
]

It's already in settings.py, but my form's password is not being validated.

like image 535
Hashir Sarwar Avatar asked Dec 15 '17 19:12

Hashir Sarwar


People also ask

How do I create a custom password validator in Django?

How To Create Your Own Django Password Validator. If you have more specific needs, you can create your own validators. To do so, simply create your own classes based on object and raise a ValidationError if the entered password fails. class NumberValidator(object): def validate(self, password, user=None): if not re.

How does Django validate password?

validate(self, password, user=None) : validate a password. Return None if the password is valid, or raise a ValidationError with an error message if the password is not valid. You must be able to deal with user being None - if that means your validator can't run, return None for no error.

Does Django automatically hash passwords?

Passwords are hashed, by default, using the PBKDF2 algorithm. However, Django provides the option to use other algorithms such as Argon2 and bcrypt.


1 Answers

in forms.py file you can use this to validate the password for all validations which have been defined in settings. if you didn't define any of the validators in the settings file then call a specific validator which you want to validate.

from django.contrib.auth.password_validation import validate_password`
from django.core import validators
from django import forms
class User_profileForm(forms.ModelForm):
password=forms.CharField(widget=forms.PasswordInput,validators=[validate_password])
like image 161
avinash Avatar answered Oct 27 '22 18:10

avinash