Automatically create username in user model in Django based on other fields

I was looking for the best practice, but I did not find it. I couldnโ€™t even find a solution that I need to use by someone else.

I need to generate the username of the user based on its other data (first and last name), adding an integer at the end if necessary, until I get a unique username.

I prefer to do this in the model. Is there a standard way to do this? Or is it fit only in uniform? I studied overloading various model methods User, as well as signals, and did not find a suitable place to add it.

+5
source share
1 answer

pre_save.

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)
+4

All Articles