I’ve a loop which checks a username.
If the username exists I want to increment the counter for each loop.
Then append that Id to the username.
This loop always returns the original argument passed though and I don’t know why. I have it going on a def save on my form in forms.py.
def check_username(self, username):
"""
check if username is taken. if it is then increment the counter and append to the username
"""
counter = 001
if User.objects.filter(username__iexact=username).exists():
counter += 1
username += str(counter)
self.check_username(username)
return username
You should probably use
return self.check_username(username)within theifblock, otherwise, your recursive call won’t do much.The counter is probably not used as you’d like here either. You’ll keep adding ‘2’ at the end of every username you try, e.g
username->username2->username22.This being said, a
whileloop would certainly be easier to read here. I’d try something like this: