我在django中使用crispy-forms工作,第一次单击提交按钮后渲染失败,第二次单击提交按钮没有响应

时间:2016-09-09 01:48:00

标签: python ajax django

我准备好使用crispy-froms到我的django投影,但是在测试中,有一个问题,我不知道发生了什么错误。所以我在这里发布代码。 如果有人可以指出错误,我会很感激。 形式:

class TestForm(forms.ModelForm):

    name = forms.CharField(widget=forms.TextInput(),label='Name',max_length=100,)

    def __init__(self,*args,**kwargs):
        super(TestForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.add_input(Button('save', 'save'))
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-3'
        self.helper.field_class = 'col-lg-8'
        self.helper.form_id = 'pkg-form'

        class Meta:
            model = PkgList
            fields = (
                'id','name',
             )

urls.py:

url(r'^testform/$',test_form,name='test_form')

我的代码中的观点:

@json_view
def test_form(request):
    if request.method == 'POST'and request.is_ajax():
        form = TestForm(request.POST)
        if form.is_valid():
            return {'success': True}
        else:
            form_html = render_crispy_form(form)
            return {'success': False, 'form_html': form_html}

    else:
        if request.method == 'GET':
            form = TestForm()
            return render(request,'man/pkg_form.html',{'form':form})

templetes:

<div class="modal-dialog" xmlns="http://www.w3.org/1999/html">
    <div class="modal-content message_align">
        <div class="modal-body" align="center">
            <span class="section">Pkg Info</span>
            {% crispy form form.helper%}
        </div>
    <div>
</div>

$('#button-id-save').on('click', function(event){
    event.preventDefault();
    var form = '#pkg-form';
    $.ajax({
        url: "{% url 'pkg_view' %}",
        type: "POST",
        data: $(form).serialize(),
        success: function(data) {
            if (!(data['success'])) {
                $(form).replaceWith(data['form_html']);
            }else {
                window.location.href = "{%url 'man/pkglist'  %}";
            }
        },
        error: function () {
            $(form).find('.error-message').show()
        }
    });
    return false;
});
在第一次ajax POST之后,从后端返回{'success':False,'form_html':form_html},点击按钮无法再发送ajax POST .....

1 个答案:

答案 0 :(得分:0)

很可能是因为你的ajax事件绑定到被返回数据替换的元素。尝试将其绑定到文档。

而不是

$('#button-id-save').on('click', function(event){ ... }

试试这个

$(document).on("click", "#button-id-save", function(event){
  ...
});