I am trying to customize Form Validation error message for Password Confirmation Field at User Creation Form.
My forms.py is like below.
from django.contrib.auth.forms import UserCreationForm
from django.core.exceptions import ValidationError
from .models import User
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ('first_name','last_name','email','date_of_birth', 'gender', 'user_type', 'phone', 'address','photo', 'password1', 'password2' )
error_messages = {
field: {
'required': f"{field.replace('_', ' ').title()} is required."
}
for field in fields
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field_name in self.fields:
self.fields[field_name].error_messages.update(self.Meta.error_messages[field_name])
My views.py is like below.
class UserRegisterView( FormView ):
template_name = 'register.html'
form_class = CustomUserCreationForm
redirect_authenticated_user = True
success_url = reverse_lazy('dashboard')
def form_valid( self, form ):
user = form.save()
if user is not None:
login( self.request, user )
return super( UserRegisterView, self ).form_valid( form )
def get( self, *args, **kwargs ):
if self.request.user.is_authenticated:
return redirect('dashboard')
return super( UserRegisterView, self ).get( *args, **kwargs )
def form_invalid(self, form):
return super(UserRegisterView, self).form_invalid(form)
My HTML code is like below.
<label class="form-label">PassWord Confirmation</label>
<input type="password" class="form-control" name="password2" />
{% if form.password2.errors %}
<div class="alert alert-danger">{{ form.password2.errors }}</div>
{% endif %}
Now I am getting validation message Password2 is required.
. But I would like to get validation message Password Confirmation is required.
.