CreateView with additional model

848 views Asked by At

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?

1

There are 1 answers

0
Daniel Roseman On BEST ANSWER

You'd need to add an extra field to your UserCreateForm:

class UserCreateForm(ModelForm):
    groups = forms.ModelMultipleChoiceField(queryset=UserGroup.objects.all())

and set it in your CreateView's form_valid method:

def form_valid(self):
    response = super(UserCreateView, self).form_valid()
    self.object.user_groups = self.form.cleaned_data['groups']
    return response