Search code examples
pythondjangodjango-allauth

Django sign up multiple users by one form


I want to sign up multiple user by enter some word at first, e.g name to start with"test_user" and the number of users "3", and it will create user "test_user1", "test_user2", "test_user3"

and this is my code


view.py

class CustomSignupView(SuccessMessageMixin, FormView):
form_class = UserCreateForm
success_url ="profile/"
template_name = "account/signup.html"

def form_valid(self, form):
    usernames = []
    username = form.cleaned_data['username']
    stuNumber = form.cleaned_data['stuNumber']

    if int(stuNumber) != 1:
        for i in range(0, int(stuNumber)):
            usernames.append(username + str(i + 1))
            form.instance.username = usernames[i]
            form.save()
    else:
        form.save()
    
    return redirect(self.success_url)

forms.py

class UserCreateForm(forms.ModelForm):
username = forms.CharField(max_length=30, label='Username')
password = forms.CharField(label='Password')
stuNumber = forms.CharField(label='StuNumber')

class Meta:
    model = user
    fields = ['username', 'stuNumber']

def generate_password(self):
    password = Account.objects.make_random_password(length=10)
    return password

def save(self, commit=True):
    user = super(UserCreateForm, self).save(commit=False)
    user.set_password(self.cleaned_data['password'])

    if commit:
        user.save()
        return user 

The problem is when I want to create 3 users, and type number 3, it only create 1 form for user3, no user1 and user2. I can't fix it, help, thanks!!


Solution

  • I think its because your form instance after being saved once just getting updated inside loop instead of initialising a new instance. The following should work, just create a new form instance each time.

    def form_valid(self, form):
        usernames = []
        username = form.cleaned_data['username']
        stuNumber = form.cleaned_data['stuNumber']
    
        if int(stuNumber) != 1:
            for i in range(0, int(stuNumber)):
                # handle if there are other fields 
                new_form = UserCreateForm({
                               'username':(username + str(i + 1)),
                              'stuNumber': i
                           })
                if new_form.is_valid():
                     new_form.save()
        else:
            form.save()
        
        return redirect(self.success_url)