Django没有从表单右侧保存多选选项

时间:2016-10-04 22:43:12

标签: python django django-forms django-views

我有一个表格,对于带有Many2Many的模型有一个选择多个选项。这似乎有效但在实际使用表单时,如果我选择多个内容并单击“保存”,则只保存其中一个项目。

他在views.py中的相关信息显示了这种情况发生的位置。

此外,事务的输出也在这里,看起来每次都在进行插入。我想我想要创造一个?虽然不确定我是否这样做(或如何)如果每次更改提供者所属的组时也会这样做。

输出:

(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

forms.py

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'}),



        }

views.py

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)

models.py

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)

1 个答案:

答案 0 :(得分:0)

您可以尝试从views.py

中的for循环中取出return语句
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)