6

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.

Tadeck
  • 132,510
  • 28
  • 152
  • 198

1 Answers1

4

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)
Ahsan
  • 11,516
  • 12
  • 52
  • 79
  • I was thinking about using that, but I am concerned with what forms will actually do with that. Forms validate the input before making call to `save()`, so the field would be treated as invalid. Btw. `obj.save()` will also call `pre_save` signal, so I you should probably remove that (or replace with something else you had in mind). – Tadeck Jul 25 '12 at 12:41
  • Your solution works, but not always (if validation is handled before save, we are out of luck) and needs adjustments (removal of `obj.save()`, and `get_unique_username` should also work if we are updating existing model). In general I think there is no better way to do that, so your answer is acceptable. Thanks. – Tadeck Jul 25 '12 at 14:50
  • Yes, now it is better (I use `obj.pk` instead of `obj.id` just for consistency with different models, where I have primary keys different than `id`; I also check if username is defined and not empty). I have already accepted your answer, now I can upvote it also :) +1 – Tadeck Jul 25 '12 at 15:47