diff --git a/accounts/forms.py b/accounts/forms.py index c47bc61fe..1285ae36e 100644 --- a/accounts/forms.py +++ b/accounts/forms.py @@ -152,13 +152,19 @@ def get_user_by_email(email): class UsernameField(forms.CharField): """ Username field, 3~30 characters, allows only alphanumeric chars, required by default """ + def __init__(self, required=True): - #NOTE: this allows space characters for both pre-existing usernames (OK) - # but also for modified new ones (not OK). It does not allow them for brand new ones (OK) + """Validates the username field for a form. Validation for brand new usernames must have strong validation (see Regex). + For profile modifications, the username validation is done in ProfileForm cleaning methods, as antique usernames can + contain spaces but new modified ones cannot. + + Args: + required (bool, optional): True for RegistrationForms, false for ProfileForms + """ if required: validators = [RegexValidator(r'^[\w.+-]+$')] # is the same as Django UsernameValidator except for '@' symbol else: - validators = [RegexValidator(r'^[\w .+-]+$')] #same as the last one but with space characters included + validators = [] super().__init__( label="Username", min_length=3, @@ -395,10 +401,16 @@ def clean_username(self): if not username: username = self.request.user.username - # If username was not changed, consider it valid + # If username was not changed, consider it valid. If it has, validate it to check it does not contain space characters. if username.lower() == self.request.user.username.lower(): - #self.fields["username"] = UsernameField(validation=False) return username + else: + validator = RegexValidator(regex=r'^[\w.+-]+$', + message="The username field must contain only letters, digits, underscores, dots, dashes and plus signs.", + code='invalid') + if validator(username): + return username + # Check that username is not used by another user. Note that because when the maximum number of username # changes is reached, the "username" field of the ProfileForm is disabled and its contents won't change.