I have been searching for best practice, but I did not found it. I was even unable to find solution I need used by anyone else.
I need to generate username of the user based on his other data (first name & last name), optionally appending integer at the end, until I get the unique username.
I strongly prefer doing that in model. Is there some standard way to do that? Or is it only appropriate in forms? I have been researching overloading of various User
model methods, as well as signals, and did not find any proper place I could add it.
One possible solution could be through pre_save signal.
def my_callback(sender, **kwargs):
obj = kwargs['instance']
if not obj.id:
username = get_unique_username(obj) # method that combines first name and last name then query on User model, if record found, will append integer 1 and then query again, until found unique username
obj.username = username
pre_save.connect(my_callback, sender=User)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With