如何将用户模型中的用户名设置为随机字符串

时间:2013-07-19 04:07:53

标签: python django django-models django-forms django-admin

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']

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

用户名字段包含在表单中。在模板中,我隐藏了用户名字段。在创建用户配置文件时,如何使用随机字符串创建用户名?

2 个答案:

答案 0 :(得分:1)

从此answer

您可以这样做:

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,})

答案 1 :(得分:0)

请查看您是否可以使用此功能。

import random
l = list(map(chr, range(97, 123))) 
random.shuffle(l)    
''.join(l)[0:7]