import string import random from authentication.models import SystemUserProfile from general_urls import base_user_gate_way_id while (True): res = ''.join(random.choices(string.ascii_lowercase + string.digits, k=5)) res = base_user_gate_way_id + res if not SystemUserProfile.objects.filter(user_gate_way_id=res).exists(): break