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.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
}
]
It's already in settings.py
, but my form's password is not being validated.
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.
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.
Passwords are hashed, by default, using the PBKDF2 algorithm. However, Django provides the option to use other algorithms such as Argon2 and bcrypt.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With