0

视图.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,})

表格.py

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

我正在通过表单保存表单字段。

用户名字段包含在表单中。在模板中,我隐藏了用户名字段。在创建用户个人资料时,如何使用随机字符串创建用户名?

4

2 回答 2

1

从这个 答案

你可以这样做:

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,})
于 2013-07-19T04:19:58.807 回答
0

请看看你是否可以使用这个。

import random
l = list(map(chr, range(97, 123))) 
random.shuffle(l)    
''.join(l)[0:7] 
于 2013-07-19T04:51:23.207 回答