Search code examples
pythondjangodjango-modelsdjango-formsdjango-allauth

Django allauth custom signup form error: 'Institution' object is not iterable


I'm probably missing something obvious here, but I'm getting the following error:

'Institution' object is not iterable

It doesn't like this line in the code:

user.institution = institution

Here's the full SignupForm class for Django allauth:

class SignupForm(forms.Form):
    first_name = forms.CharField(
        max_length=255,
        label="Your First Name",
    )
    last_name = forms.CharField(
        max_length=255,
        label="Your Last Name",
    )
    institution = forms.ModelChoiceField(
        label="Your Institution",
        queryset=Institution.objects.all(),
        empty_label="Other Institution Not Listed",
    )

    def signup(self, request, user):
        from pprint import pprint
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.institution = self.cleaned_data['institution']

        user.save()

I've checked self.cleaned_data and it appears to be passing the institution correctly:

{'email': 'blah@blah',
 'first_name': 'John',
 'institution': <Institution: Blah College>,
 'last_name': 'Doe'}

I'm using a custom user model and institution is a many-to-many:

institution = models.ManyToManyField(Institution, db_index=True)

Any ideas? What am I doing wrong here?


Solution

  • If its a ManyToMany relationship then you need to use the add method to associate an institution with the user:

    user.institution.add(self.cleaned_data['institution'])
    

    You can read more about operations on Many-to-many relationships here.