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.