【问题标题】:Django not saving the multi-select option from form rightDjango没有从表单右侧保存多选选项
【发布时间】:2016-10-04 22:43:12
【问题描述】:

我有一个表单,该表单具有多选选项,适用于具有 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)

【问题讨论】:

    标签: python django django-forms django-views


    【解决方案1】:

    您可以尝试将 return 语句从您的 views.py 中的 for 循环中取出

    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)
    

    【讨论】:

    • 哇,好吧,在哪里?哪条线?我需要保存吗?哦,不是 = 而是加号吗?
    • 啊,好吧,我在这里看到了问题,我的模型不是微不足道的。让我发布更多模型来展示。很快我得到了这个错误:ProviderLocations has no group_location。现在添加位置模型...
    • 是的,对 ManyToManyFields 使用“add”。您的 location.save() 应该可以正常工作
    • 哦,我看到您的模型中有 group_locations,抱歉,打错了,请执行 location.group_locations.add(group_location)
    • 我认为 django 对一些约定命名很感兴趣,再次得到:'ProviderLocations' 对象没有属性 'group_locations' 我需要像 group_group_location 之类的吗?
    猜你喜欢
    • 1970-01-01
    • 2021-11-16
    • 2011-08-10
    • 2011-11-30
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多