pythondjangodjango-formsdjango-usersdjango-registration

Populate Django username field with generated username


I would like the user name field for my Django registration to populate with the following function -

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

I am currently using the UserRegisterForm model from Django and would prefer to find away to integrate into this, however if the best option is to custom my own user model then I am happy to do this also.

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

Solution

  • You can set this to the user object wrapped in the form:

    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.instance.username = username
                form.save()
                messages.success(request, f'Account created for {username}')
                return redirect('login')