@@ -152,12 +152,24 @@ def get_user_by_email(email):
152152
153153class UsernameField (forms .CharField ):
154154 """ Username field, 3~30 characters, allows only alphanumeric chars, required by default """
155+
155156 def __init__ (self , required = True ):
157+ """Validates the username field for a form. Validation for brand new usernames must have strong validation (see Regex).
158+ For profile modifications, the username validation is done in ProfileForm cleaning methods, as antique usernames can
159+ contain spaces but new modified ones cannot.
160+
161+ Args:
162+ required (bool, optional): True for RegistrationForms, false for ProfileForms
163+ """
164+ if required :
165+ validators = [RegexValidator (r'^[\w.+-]+$' )] # is the same as Django UsernameValidator except for '@' symbol
166+ else :
167+ validators = []
156168 super ().__init__ (
157169 label = "Username" ,
158170 min_length = 3 ,
159171 max_length = 30 ,
160- validators = [ RegexValidator ( r'^[\w.+-]+$' )], # is the same as Django UsernameValidator except for '@' symbol
172+ validators = validators ,
161173 help_text = "30 characters or fewer. Can contain: letters, digits, underscores, dots, dashes and plus signs." ,
162174 error_messages = {'invalid' : "The username field must contain only letters, digits, underscores, dots, dashes and "
163175 "plus signs." },
@@ -389,9 +401,16 @@ def clean_username(self):
389401 if not username :
390402 username = self .request .user .username
391403
392- # If username was not changed, consider it valid
404+ # If username was not changed, consider it valid. If it has, validate it to check it does not contain space characters.
393405 if username .lower () == self .request .user .username .lower ():
394406 return username
407+ else :
408+ validator = RegexValidator (regex = r'^[\w.+-]+$' ,
409+ message = "The username field must contain only letters, digits, underscores, dots, dashes and plus signs." ,
410+ code = 'invalid' )
411+ if validator (username ):
412+ return username
413+
395414
396415 # Check that username is not used by another user. Note that because when the maximum number of username
397416 # changes is reached, the "username" field of the ProfileForm is disabled and its contents won't change.
0 commit comments