I am creating a system with Django. I already created a login page in the beginning of the project. But now, I realized that I have no conditions for password field. I want to put some restrictions like 8 characters, uppercase and lowercase letters and numbers. How can I check this when user fills the form?
forms.py
class SignUpForm(forms.ModelForm):
password1 = forms.CharField(max_length=250, min_length=8, widget=forms.PasswordInput)
password2 = forms.CharField(max_length=250, min_length=8, widget=forms.PasswordInput)
...
models.py
class UserProfile(AbstractUser, UserMixin):
...
last_name = models.CharField(max_length=200)
password = models.CharField(max_length=250)
views.py
def signup(request):
current_user = request.user
new_user = UserProfile(company=current_user.company)
form = SignUpForm(request.POST or None, user=request.user, instance=new_user)
rank_list = Rank.objects.filter(company=current_user.company)
if request.method == 'POST':
if form.is_valid():
form.instance.username = request.POST.get('email', None)
new_user = form.save()
...
}
return render(request, 'signup.html', context)
EDIT
I added codes according to the answers but It did not works.
settings.py
AUTH_PASSWORD_VALIDATORS = [
{'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
'OPTIONS': {
'min_length': 12, }
},
{'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', },
{'NAME': 'register.validators.UppercaseValidator', },
{'NAME': 'register.validators.NumberValidator', },
{'NAME': 'register.validators.LowercaseValidator', },
]
register/validators.py
import re
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
class NumberValidator(object):
def __init__(self, min_digits=0):
self.min_digits = min_digits
def validate(self, password, user=None):
if not len(re.findall('\d', password)) >= self.min_digits:
raise ValidationError(
_("The password must contain at least %(min_digits)d digit(s), 0-9."),
code='password_no_number',
params={'min_digits': self.min_digits},
)
def get_help_text(self):
return _(
"Your password must contain at least %(min_digits)d digit(s), 0-9." % {'min_digits': self.min_digits}
)
class UppercaseValidator(object):
def validate(self, password, user=None):
if not re.findall('[A-Z]', password):
raise ValidationError(
_("The password must contain at least 1 uppercase letter, A-Z."),
code='password_no_upper',
)
def get_help_text(self):
return _(
"Your password must contain at least 1 uppercase letter, A-Z."
)
class LowercaseValidator:
def validate(self, password, user=None):
if not re.findall('[a-z]', password):
raise ValidationError(
_("The password must contain at least 1 lowercase letter, a-z."),
code='password_no_lower',
)
def get_help_text(self):
return _(
"Your password must contain at least 1 lowercase letter, a-z."
)