On Jan 14, 2010, at 6:45 AM, nameless wrote: > > > I want username field is automatically filled with this value: > > username = str(n); > > where n is a number of 10 digits ( autoincremented or random ). > > . > > I tried to add this in save method: > > username = str(random.randint(1000000000,9999999999)) > > but there is a collision problem when n is the same for 2 users > ( although rare initially ). > > . > > How do I do this ? >
We did something like: def register_user(email, password, first_name=None, last_name=None, agree_to_eula=True): def generate_username(): """Generate a random 30-character username. Username can only be alphanumeric or underscore.""" return ''.join([choice(string.letters + string.digits + '_') for i in range(30)]) email = email.strip() if not email_re.search(email): raise InvalidEmailAddressExcept if len(password.strip()) < 6: #TODO: pass password length info back to exception, so it's not hard coded in two locations raise InvalidPasswordExcept try: user = authenticate_user(email,password,agree_to_eula) except AuthenticationFailedExcept: raise AccountExistsAuthenticationFailedExcept except UserNotFoundExcept: # we need to create this user while True: try: user = User.objects.create_user(username=generate_username(), email=email, password=password) except IntegrityError: # this means the username already exists loop and try again with a new username continue else: # we successfully created the user, leave the loop break if first_name: user.first_name = first_name if last_name: user.last_name = last_name user.save() profile = Profile(user=user) if agree_to_eula: profile.agree_to_eula() profile.save() else: profile = user.get_profile() return {'user': user,}
-- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.