Django not saving the multi-select option from form right
<p>I have a form that has a select multiple option for a model with a Many2Many.  This seems to work but upon actually using the form if I select multiple things and click save, it only saves one of the items.</p>

<p>The pertinent info int he views.py is located showing where this is happening.</p>

<p>Also the output from the transaction is here, it looks like it is doing an insert every time.  I think I want to fore a create?  Though not sure if I did that (or how to) if it would also do that every time the change what groups the provider belongs to.</p>

<p>Output:</p>

<pre><code>(0.000) BEGIN; args=None
(0.001) DELETE FROM "ipaswdb_providerlocations" WHERE "ipaswdb_providerlocations"."provider_id" = 1; args=(1,)
here!IPANM
Made a location!
here!IPAABQ
Made a location!
(0.000) BEGIN; args=None
(0.000) INSERT INTO "ipaswdb_providerlocations" ("provider_id", "group_location_id", "created_at", "updated_at") VALUES (1, 2, '2016-10-04', '2016-10-04'); args=[1, 2, u'2016-10-04', u'2016-10-04']
Id: 42
</code></pre>

<p>forms.py</p>

<pre><code>class ProviderForm(forms.ModelForm):

    phone = forms.RegexField(required=False, regex=r'^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$', 
                                        error_message = ("Phone number must be entered in the format: '555-555-5555 or 5555555555'. Up to 15 digits allowed."),
                                        widget = forms.TextInput(attrs={'tabindex':'8', 'placeholder': '555-555-5555 or 5555555555'}))

    fax = forms.RegexField(required=False, regex=r'^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$', 
                                     error_message = ("Fax number must be entered in the format: '555-555-5555 or 5555555555'. Up to 15 digits allowed."),
                                    widget = forms.TextInput(attrs={'tabindex':'9', 'placeholder': '555-555-5555 or 5555555555'}))

    class Meta:
        model=Provider



        fields = ('first_name', 'last_name', 'date_of_birth', 'license_number', 'license_experation', 'dea_number', 'dea_experation', 'phone',
                    'fax', 'caqh_number', 'effective_date', 'provider_npi', 'provisional_effective_date', 'date_joined', 'provider_contact',
                    'credentialing_contact', 'notes', 'hospital_affiliation', 'designation', 'specialty', 'group_locations')
        widgets = {

            'designation' : Select(attrs={'tabindex':'1'}),

            'first_name': TextInput(attrs={'tabindex':'2', 'placeholder':'Provider\'s first name'}),
            'last_name' : TextInput(attrs={'tabindex':'3', 'placeholder':'Provider\'s last name'}),
            'specialty' : Select(attrs={'tabindex':'4'}),

            'date_of_birth' : TextInput(attrs=
                                {
                                    'class':'datepicker',
                                    'tabindex' : '5',
                                    'placeholder' : 'MM/DD/YYYY'
                                }),

            'license_number': TextInput(attrs={'tabindex':'6', 'placeholder':'License #'}),
            'license_experation' : TextInput(attrs=
                                {
                                    'class':'datepicker',
                                    'tabindex' : '7',
                                    'placeholder' : 'MM/DD/YYYY'
                                }),         


            'dea_number' : TextInput(attrs={'tabindex':'8', 'placeholder':'DEA #'}),

            'dea_experation' : TextInput(attrs=
                                {
                                    'class':'datepicker',
                                    'tabindex' : '9',
                                    'placeholder' : 'MM/DD/YYYY'
                                }),             
            'ptan': TextInput(attrs={'tabindex':'10', 'placeholder':'Provider\'s PTAN #'}),
            'caqh_number': TextInput(attrs={'tabindex':'11', 'placeholder':'Provider\'s CAQH #'}),

            'effective_date' : TextInput(attrs=
                                {
                                    'class':'datepicker',
                                    'tabindex' : '12',
                                    'placeholder' : 'MM/DD/YYYY'
                                }),
            'provider_npi': TextInput(attrs={'tabindex':'13', 'placeholder':'Provider\'s NPI #'}),


            'provisional_effective_date' : TextInput(attrs=
                                {
                                    'class':'datepicker',
                                    'tabindex' : '14',
                                    'placeholder' : 'MM/DD/YYYY'
                                }),

            'date_joined' : TextInput(attrs=
                                {
                                    'class':'datepicker',
                                    'tabindex' : '15',
                                    'placeholder' : 'MM/DD/YYYY'
                                }),
            'provider_contact': TextInput(attrs={'tabindex':'16', 'placeholder':'Provider\'s Contact'}),
            'credentialing_contact': TextInput(attrs={'tabindex':'17', 'placeholder':'Credentialer\'s Contact'}),

            'notes' : Textarea(attrs={'tabindex':'18', 'placeholder':'Provider\'s notes'}),

            'hospital_affiliation': TextInput(attrs={'tabindex':'19', 'placeholder':'Provider\'s Hospital Affiliation'}),



        }
</code></pre>

<p>views.py</p>

<pre><code>class ProviderUpdateView(UpdateView):
    model = Provider
    form_class = ProviderForm
    template_name = 'ipaswdb/provider/provider_form.html'
    success_url = 'ipaswdb/provider/'


    def form_valid(self, form):
        self.object = form.save(commit=False)
        ProviderLocations.objects.filter(provider=self.object).delete()
        for group_location in form.cleaned_data['group_locations']:
            print("here!" + group_location.doing_business_as)
            location = ProviderLocations()
            print("Made a location!") #executes twice
            location.provider = self.object
            location.group_location = group_location
            location.save()
            print("Id: " + str(location.id))  #executes once

            return super(ModelFormMixin, self).form_valid(form)
</code></pre>

<p>models.py</p>

<pre><code>class Provider(models.Model):
    first_name = models.CharField(max_length = 50)
    last_name = models.CharField(max_length = 50)
    date_of_birth = models.DateField(auto_now_add=False)
    license_number = models.CharField(max_length = 50)
    license_experation= models.DateField(auto_now_add=False)
    dea_number = models.CharField(max_length = 50)
    dea_experation = models.DateField(auto_now_add=False)
    phone = models.CharField(max_length = 50)
    fax = models.CharField(max_length = 50, null=True, blank=True)
    ptan = models.CharField(max_length = 50)
    caqh_number = models.CharField(max_length = 50)
    effective_date = models.DateField(auto_now_add=False)
    provider_npi = models.CharField(max_length = 50)
    provisional_effective_date = models.DateField(auto_now_add=False)
    date_joined = models.DateField(auto_now_add=False)
    provider_contact = models.CharField(max_length = 50, blank=True, null=True)
    credentialing_contact = models.CharField(max_length = 50, blank=True, null=True)
    notes = models.TextField(max_length = 255, blank=True, null=True)
    hospital_affiliation= models.CharField(max_length = 50, null=True, blank=True)
    designation = models.ForeignKey('Designation', on_delete=models.SET_NULL, null=True, blank=True)
    specialty = models.ForeignKey('Specialty', on_delete=models.SET_NULL, null=True, blank=True)
    group_locations = models.ManyToManyField('GroupLocations', through='ProviderLocations', blank=True, null=True)
    created_at=models.DateField(auto_now_add=True)
    updated_at=models.DateField(auto_now=True)
    def __str__(self):
        return self.first_name

#really think this is just broken too I really want something like the 
#screen in billings for the provider to have a manytomany field on the grouplocations
#do i need a special method to get this data together or can i do it through through fields??  
#look at billings when it boots up.
class ProviderLocations(models.Model):
        #group_location = models.ForeignKey('GroupLocations', on_delete=models.CASCADE)
    provider = models.ForeignKey('Provider', on_delete=models.CASCADE)
    group_location = models.ForeignKey('GroupLocations', on_delete=models.CASCADE)
    created_at=models.DateField(auto_now_add=True)
    updated_at=models.DateField(auto_now=True)
    def __str__(self):
        return self.provider.first_name

#i really think provider should go away here
class GroupLocations(models.Model):
    address = models.ForeignKey('Address', on_delete= models.SET_NULL, null=True)
    group = models.ForeignKey('Group', on_delete=models.CASCADE)
    doing_business_as = models.CharField(max_length = 255)
    created_at=models.DateField(auto_now_add=True)
    updated_at=models.DateField(auto_now=True)
    def __str__(self):
        return self.doing_business_as


class Group(models.Model):
    group_name = models.CharField(max_length=50)
    group_contact= models.CharField(max_length=50)
    tin = models.CharField(max_length=50)


class Address(models.Model):
    city = models.CharField(max_length=50)
    state = models.CharField(max_length=50)
    zip_code = models.CharField(max_length=50)
</code></pre>

<p>You might try taking the return statement out of the for loop in your views.py</p>

<pre><code>def form_valid(self, form):
    self.object = form.save(commit=False)
    ProviderLocations.objects.filter(provider=self.object).delete()
    for group_location in form.cleaned_data['group_locations']:
        print("here!" + group_location.doing_business_as)
        location = ProviderLocations()
        print("Made a location!") #executes twice
        location.provider = self.object
        location.group_location = group_location
        location.save()
        print("Id: " + str(location.id))  #executes once

    return super(ModelFormMixin, self).form_valid(form)
</code></pre>

python django django-forms django-views