@@ -152,12 +152,24 @@ def get_user_by_email(email):
152
152
153
153
class UsernameField (forms .CharField ):
154
154
""" Username field, 3~30 characters, allows only alphanumeric chars, required by default """
155
+
155
156
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 = []
156
168
super ().__init__ (
157
169
label = "Username" ,
158
170
min_length = 3 ,
159
171
max_length = 30 ,
160
- validators = [ RegexValidator ( r'^[\w.+-]+$' )], # is the same as Django UsernameValidator except for '@' symbol
172
+ validators = validators ,
161
173
help_text = "30 characters or fewer. Can contain: letters, digits, underscores, dots, dashes and plus signs." ,
162
174
error_messages = {'invalid' : "The username field must contain only letters, digits, underscores, dots, dashes and "
163
175
"plus signs." },
@@ -389,9 +401,16 @@ def clean_username(self):
389
401
if not username :
390
402
username = self .request .user .username
391
403
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.
393
405
if username .lower () == self .request .user .username .lower ():
394
406
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
+
395
414
396
415
# Check that username is not used by another user. Note that because when the maximum number of username
397
416
# changes is reached, the "username" field of the ProfileForm is disabled and its contents won't change.
0 commit comments