使用生成的用户名填充 Django 用户名字段

Populate Django username field with generated username

我希望使用以下函数填充我的 Django 注册的用户名字段 -

def generateUsername():
    username =  firstname[0] + middlename[0] + lastname[0] + randomStringDigits(6) + getDateTimeStr()
    return username

我目前正在使用 Django 的 UserRegisterForm 模型,并且更愿意找到方法集成到其中,但是如果最好的选择是自定义我自己的用户模型,那么我也很乐意这样做。

views.py -

def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account created for {username}')
            return redirect('login')
    else:
        form = UserRegisterForm()
    return render(request, 'users/register.html', {'form': form})

forms.py -

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()
    firstname = forms.CharField(max_length=20)
    middlename = forms.CharField(max_length=20)
    lastname = forms.CharField(max_length=20)

    class Meta:
        model = User
        fields = ['email', 'firstname', 'middlename', 'lastname']

您可以将此设置为包装在表单中的用户对象:

def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            username = f"{data['firstname'][0]}{data['middlename'][0]}{data['lastname'][0]}{randomStringDigits(6)}"
            form<b>.instance.username</b> = username
            form.save()
            messages.success(request, f'Account created for {username}')
            return redirect('login')