Skip to content

Commit

Permalink
enable profile updates for antique usernames containing spaces
Browse files Browse the repository at this point in the history
  • Loading branch information
quimmrc committed Dec 13, 2024
1 parent 65a055c commit 6a51d80
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions accounts/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down

0 comments on commit 6a51d80

Please sign in to comment.