簡體   English   中英

我在Django中使用crispy-forms工作,第一次單擊提交按鈕后渲染失敗,第二次單擊提交按鈕沒有響應

[英]I use crispy-forms work in django,render failures after the first click the submit button,the second time click the submit button has no response

我已經准備好使用crisp-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})

廟宇:

<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。

這很可能是因為您的ajax事件綁定到了一個元素,該元素正被返回的數據替換。 嘗試將其綁定到文檔。

代替

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

嘗試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM