开发者

Insert AUTOMATICALLY random string in username field

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 pro开发者_JAVA技巧blem when n is the same for 2 users.

How do I do this ?


Here is a modified version of the generate username method that allows you to create more human-readable usernames just in case you are using it as an identifier for any purpose.

from random import choice
from string import ascii_lowercase, digits
from django.contrib.auth.models import User

def generate_random_username(length=16, chars=ascii_lowercase+digits, split=4, delimiter='-'):

    username = ''.join([choice(chars) for i in xrange(length)])

    if split:
        username = delimiter.join([username[start:start+split] for start in range(0, len(username), split)])

    try:
        User.objects.get(username=username)
        return generate_random_username(length=length, chars=chars, split=split, delimiter=delimiter)
    except User.DoesNotExist:
        return username;


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;


Based on Antony Hatchkins comments I implemented a similar algo recently, figured I'd post for feedback, looped with failure protection instead of recursive without protection:

def GenerateUsername():
    i = 0
    MAX = 1000000
    while(i < MAX):
        username = str(random.randint(0,MAX))
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        i+=1
    raise Exception('All random username are taken')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜