MiniGunnR
MiniGunnR

Reputation: 5800

How to save ModelMultipleChoiceField in Django view?

I have a Subject model and a CustomUser model. During registration users can select multiple subjects. The following is my code in forms.

forms.py

class SignUpForm(forms.Form):
    ...
    subjects = forms.ModelMultipleChoiceField(label="Subjects",
                                         widget=forms.CheckboxSelectMultiple,
                                         queryset=Subject.objects.all())

What can I do in views.py to save this data? The usual method of cleaning the data and then using the save method doesn't work unfortunately. Scarily, similar questions have very little to no answers in SO.

Upvotes: 1

Views: 700

Answers (1)

MiniGunnR
MiniGunnR

Reputation: 5800

Nevermind. I found it.

if password == password2:
                u = CustomUser.objects.create_user(username, email, password, first_name=fname, last_name=lname, dob=year+'-'+month+'-'+day)
                u.subjects = subjects
                u.save

I made the mistake of trying to squeeze in the subjects in the create_user method with all the other variables.

Upvotes: 0

Related Questions