0

views.py

def index(request):
    registerform = UserRegisterForm()
    if request.method == 'POST':
        if 'password' in request.POST:
            registerform = UserRegisterForm(request.POST)    
            if registerform.is_valid():
                result = registerform.save(commit=False)
                result.set_password(request.POST['password'])       
                result.save()
                member.user_id = user.id
                member.member_id = result.id
                member.save() 
          ''''
    return render(request,'index.html',{'registerform': registerform,})

forms.py

class UserRegisterForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username','first_name', 'last_name', 'email', 'password', 'is_staff', 'is_active']

I am saving the form fields via form.

The username field is included in the form. In the template, I made the username field hidden. How would I create a username with random string while creating the user profile?

user2086641
  • 4,331
  • 13
  • 56
  • 96
  • Read the first answer http://stackoverflow.com/questions/2257441/python-random-string-generation-with-upper-case-letters-and-digits – Victor Castillo Torres Jul 19 '13 at 04:16
  • Why not try to set first part(before `@`) of user `Email` as username and if exists bump the suffix by appending an integer until you don't get a unique username? In this way the usernames will be at-least readable as you are taking it from an email. – Aamir Rind Jul 19 '13 at 05:04
  • @AamirAdnan,great suggestion. – user2086641 Jul 19 '13 at 05:26

2 Answers2

1

From this answer

You can do something like this:

import random
import string

def index(request):
    registerform = UserRegisterForm()
    if request.method == 'POST':
        if 'password' in request.POST:
            registerform = UserRegisterForm(request.POST)    
            if registerform.is_valid():
                username = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10))
                result = registerform.save(commit=False)
                result.set_password(request.POST['password'])
                result.username = username       
                result.save()
                member.user_id = user.id
                member.member_id = result.id
                member.save() 
          ''''
    return render(request,'index.html',{'registerform': registerform,})
Community
  • 1
  • 1
Victor Castillo Torres
  • 10,581
  • 7
  • 40
  • 50
0

Please see if you can use this.

import random
l = list(map(chr, range(97, 123))) 
random.shuffle(l)    
''.join(l)[0:7] 
Victor Castillo Torres
  • 10,581
  • 7
  • 40
  • 50