0

这个话题已经讨论过好几次了,但我似乎无法让它发挥作用:

如何在 twitter-bootstrap 模式窗口中插入 django 表单?

带有引导程序和 django 的异步表单

Twitter-Bootstrap 模式中的简单 Django 表单

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

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

我的表格:

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

视图 - UpdateView 继承了 django 文档中的 AjaxableResponseMixin:

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; 
    });
});

我不确定为什么return false;在 js 中没有抑制表单提交。我尝试使用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
    });
});
4

1 回答 1

2

我看到,表单是在模态中动态加载的。在这种情况下,您需要在表单呈现到浏览器后绑定提交事件处理程序或使用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
    });
});

希望能帮助到你。

于 2013-08-13T18:13:38.820 回答