views:

145

answers:

1

I want username field is automatically filled with this value:

username = str(n);

where n is a number ( autoincremented or random ).

.

I tried to add this in save method:

username = str(random.randint(0,1000000)

but there is a collision problem when n is the same for 2 users.

.

How do I do this ?

Thanks ^_^

+1  A: 

Generate it username = str(random.randint(0,1000000) and check for a user with such a name User.objects.get(username=username) if you find someone, generate a new one.

def GenerateUsername():
    username = str(random.randint(0,1000000))

    try:
        User.objects.get(username=username)
        return GenerateUsername()
    except User.DoesNotExist:
        return username;
Balon
it will result in stack overflow for 1000000 users
Antony Hatchkins
that's true. I didn't say that it is perfect, I've only answered his question :)
Balon
I didn't say you're wrong, I only say that an ordinary loop would be less memory-hungry in this particular case :)
Antony Hatchkins