How to add reverse many to many field with extra fields to a User ModelForm.

I’m trying to create a dashboard that allows a user with a specific role in a organization to create more users, and assign their desired role and organization in the same form.

models.py:

class User(AbstractUser):
    pass

class Organization(models.Model):
    name = models.CharField(max_length=255)
    users = models.ManyToManyField(User, through="Role")

class Role(models.Model):
    class UserRole(models.TextChoices):
        ADMIN = "admin", "Admin"
        MANAGER = "manager", "Manager"
        EMPLOYEE = "employee", "Employee"

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
    role = models.CharField(max_length=255, choices=UserRole.choices)

forms.py:

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ["email", "password"]  # can't add organization_set, or organization if I specify a `related_name`

views.py:

class UserCreateView(CreateView):
    model = User
    form_class = UserForm
    template_name = "create.html"
    success_url = reverse_lazy("index")

The problem I’m having is that I can’t add the reverse many to many field to the ModelForm, and even if I could I’m not sure how it’d handle the Role table.

I ended up making another form for role RoleForm with organization and role as fields and then making a functional view where I render both of those forms, and after validating both, assigning the returned user from the saved UserForm to the form instance of RoleForm. I wrapped the saving of both forms inside a transaction.atomic(). I’d have preferred to have a CBV, and I’m not sure if this is the correct way of doing it but although it’s ugly it works.