jQUery + Django模式窗体异步提交无页面刷新

时间:2013-08-13 06:57:34

标签: jquery ajax django submit modal-dialog

这个主题已经多次得到解决,但我似乎无法让它发挥作用:

How do I insert a django form in twitter-bootstrap modal window?

Asynchronous forms with bootstrap and django

Simple Django form in Twitter-Bootstrap modal

http://www.micahcarrick.com/ajax-form-submission-django.html

我有一个项目表,每行都附有一个编辑按钮。单击时,将显示UpdateView的模式窗体。我能够检索正确的记录,但在提交时,我无法获得aysnc提交,使页面不重定向。

我的表格:

class RSVPForm(forms.ModelForm):
    class Meta:
        model=RSVP
        fields = ['status', 'notes', 'comments']

Views - 继承django docs中的AjaxableResponseMixin的UpdateView:

import json

from django.http import HttpResponse
from braces.views import LoginRequiredMixin
from django.views.generic import UpdateView

class AjaxableResponseMixin(object):
    def render_to_json_response(self, context, **response_kwargs):
        data = json.dumps(context)
        response_kwargs['content_type'] = 'application/json'
        return HttpResponse(data, **response_kwargs)

    def form_invalid(self, form):
        response = super(AjaxableResponseMixin, self).form_invalid(form)
        if self.request.is_ajax():
            return self.render_to_json_response(form.errors, status=400)
        else:
            return response

    def form_valid(self, form):
        response = super(AjaxableResponseMixin, self).form_valid(form)
        if self.request.is_ajax():
            data = {
                'pk': self.object.pk,
            }
            return self.render_to_json_response(data)
        else:
            return response

class RSVPUpdateView(LoginRequiredMixin, AjaxableResponseMixin, UpdateView):
    model = RSVP
    form_class = RSVPForm
    template_name = 'rsvp/rsvp_modal.html'
    success_url = reverse_lazy('rsvp:rsvp_list')

JS:

$(document).ready(function(){
    $('.rsvp-form').submit(function() {
        $.ajax({ 
            type: $(this).attr('method'), 
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function() { // on success..
                $('#success_div').append('Changes saved'); // update the DIV
                $('#success_div').toggleClass('alert alert-success'); // unhide
            },
            error: function(xhr, ajaxOptions, thrownError) { // on error..
                $('#error_div').append(xhr); // update the DIV
                $('#error_div').toggleClass('alert alert-error'); // unhide
            }
        });
        return false; 
    });
});

我不确定为什么js中的return false;不会抑制表单提交。我尝试使用e.preventDefault();但没有结果。我认为这是一个疏忽的地方,如果有人能发现它,我会很感激。也许改变了AjaxableResponseMixin?

修改:添加模板

在模态表格的模板中:

{% load crispy_forms_tags %}
<div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
         <div id="success_div" class="alert alert-success hide"><button type="button" class="close" data-dismiss="alert">&times;</button></div>
         <div id="error_div" class="alert alert-error hide"><button type="button" class="close" data-dismiss="alert">&times;</button></div>
         <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
         <h4 class="modal-title">RSVP Details</h4>
      </div>
      <!-- form here -->
      <form class="rsvp-form" method="post" action="{% url 'rsvp:rsvp_update' pk=form.instance.id %}">
      <div class="modal-body">
         {% crispy form form.helper %}
      </div>
      <div class="modal-footer">
        <input class="btn btn-primary" id="modal-submit" type="submit" value="Save" />
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
      </form>
    </div>
</div>

使用以下js显示此表单:

$(document).ready(function(){
    $('.edit-modal').click(function(ev) { // for each update url
        ev.preventDefault(); // prevent navigation
        var url = $(this).data('form'); // get the update form url
        $('#RSVPModal').load(url, function() { // load the url into the modal
            $(this).modal('show'); // display the modal on url load
        });
        return false; // prevent click propagation
    });
});

1 个答案:

答案 0 :(得分:1)

我看到,表单是以模态动态加载的。在这种情况下,您需要在将表单呈现到浏览器或使用on()后绑定提交事件处理程序:

$(document).ready(function(){
    // use on() to bind event handler here
    $('#RSVPModal').on('submit', '.rsvp-form', function () {
        $.ajax({
            type: $(this).attr('method'), 
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function() { // on success..
                $('#success_div').append('Changes saved'); // update the DIV
                $('#success_div').toggleClass('alert alert-success'); // unhide
            },
            error: function(xhr, ajaxOptions, thrownError) { // on error..
                $('#error_div').append(xhr); // update the DIV
                $('#error_div').toggleClass('alert alert-error'); // unhide
            }
        });
        return false; 
    });

    $('.edit-modal').click(function(ev) { // for each update url
        ev.preventDefault(); // prevent navigation
        var url = $(this).data('form'); // get the update form url
        $('#RSVPModal').load(url, function() { // load the url into the modal
            $(this).modal('show'); // display the modal on url load
        });
        return false; // prevent click propagation
    });
});

希望它有所帮助。