I'm using a CreateView to create a User.
views.py:
class UserCreateView(CreateView):
model = User
form_class = UserCreateForm
success_url = reverse_lazy('patient:users')
forms.py
class UserCreateForm(ModelForm):
class Meta:
model = User
fields = ['first_name', 'last_name']
I have another model, UserGroups, defined as follows:
class UserGroup(models.Model):
users = models.ManyToManyField(User, blank=True, related_name='user_groups')
name = models.CharField(max_length=50)
The problem is that I would like to have the possibility to assign UserGroups to the User in the UserCreateForm. Doing this:
class UserCreateForm(ModelForm):
class Meta:
model = User
fields = ['first_name', 'last_name', 'user_groups']
does not seem to work.
What would be the best way to do this?
You'd need to add an extra field to your UserCreateForm:
and set it in your CreateView's
form_valid
method: