使用inlineformset_factory和Jquery AJAX编辑具有外键的表条目

时间:2016-09-28 00:00:32

标签: jquery python ajax django

我一直在Django开发一个简单的地址簿应用程序。我希望有一个联系人姓名,通过外键连接到该联系人的任意数量的地址...直截了当。

我的问题是,当inlineformset POST到服务器时,它总是添加一个新的表条目,尽管表单已经加载并正确初始化。

例如,如果联系人有工作地址和家庭住址,我会尝试编辑'现有工作地址... POST视图使用所有更新的信息创建第二个工作地址,我尝试编辑的原始条目仍然存在,未触及。这是我的代码......我错过了什么。

Model.py

class ContactForm(forms.ModelForm):
       class Meta:
       model = Contact
       fields = ('__all__')

class AddressForm(forms.ModelForm):
       class Meta:
       model = Address
       fields = ('contact','address_name')

AddressFormSet = modelformset_factory(
    Address,
    AddressForm,)

AddressInlineFormSet = inlineformset_factory(
    Contact,
    Address,
    fields=('address_name',),
    extra=0,
    min_num=1,
    max_num=1,
    can_delete=True)

我在outlook.py

中的条件

我认为这是问题...当我编辑如何将表单地址表单与地址输入对齐?

        if request.method == 'POST':

        ## On a POST, Retrieve the QueryDict data coming from AJAX POST
        JSON_Datalist = request.POST
        ## Convert the Data to a Dict
        jsonString = json.loads( json.dumps(JSON_Datalist))
        formdata = jsonString['form_data']
        ## Load the cleaned list into a Dict
        formdata_dict = json.loads(formdata)

        if formdata_dict['address_set-0-contact'] is not None:
            contact = get_object_or_404(Contact, pk=formdata_dict['address_set-0-contact'])

        contactformset = ContactForm(data=formdata_dict, instance=contact)

        # Have we been provided with a valid form?
        if contactformset.is_valid():
            # Save the new contact to the database.
            contactformset.save()

            addressformset=AddressInlineFormSet(data=formdata_dict,queryset=contactformset.instance.address_set.all(),instance=contact)

            if addressformset.is_valid():
                addressformset.save(commit=False)
                addressformset.contact=contact
                addressformset.save()
            else:
                print("Address Form is NOT Valid")
                print addressformset.errors

            return render(request, 'address_book/address_book.html', contacts_dict)
        else:
            # The supplied form contained errors - just print them to the terminal.
            if not contact_form.is_valid():
                print("Contact Form errors")
                print(contact_form)
                print("")
            if not addressformset.is_valid():
                print("Address Form errors")
                print(addressformset)

Jquery w / AJAX

if(buttonValue == 'UpdateButton') {
        $( 'form' ).submit(function( event ) {
            var $form = ( $(this) ).serializeArray(),
                formdata = { },
                JSONformdata;
            //Prevent Page refresh
            event.preventDefault(); 
            //Build Dictionary
            $.each($form, function(key, value) {
                formdata[value.name] = value.value;
            });
            JSONformdata = JSON.stringify(formdata);
            $.post({
                    url:'/addressbook/',
                    data: { 
                        form_data : JSONformdata,
                        csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                    },
                success: function(json) {
                    $('form#entry_form').remove();
                    console.log("success post")
                }
            })
            .fail(function() {
            console.log("failure");
            })
        }) ;
    }

0 个答案:

没有答案