Django通用视图+ JQueryUI Dialog + Ajax

时间:2012-02-25 19:02:41

标签: jquery ajax django

任何人都可以提供快速浏览吗?

我有一个JQueryUI对话框,通过带有django表单的ajax加载。

jquery的

$("#project_add").on(
    "click", {url: "/projects/project_create"}, open_dialog
);

function open_dialog(event) {
    //create the div that will hold the dialog box
    var projectDialog = $('#project_dialog');
    if ($('#project_dialog').length == 0) {
        projectDialog = $('<div id="project_dialog"></div>').appendTo('body');
    }

    // load the passed url into the dialog
    projectDialog.load(event.data.url);

    // create the dialog box and display it
    projectDialog.dialog({
        title: "Create Project",
        position: ['center', 'top'],
        closeOnEscape: true,
        close: function() {projectDialog.dialog("destroy");}
    });
}

django视图

class CreateProject(CreateView):
template_name = "projects/project_create.html"
form_class = ProjectCreateForm

def form_valid(self, form):
    self.object = form.save()
    return HttpResponse()

django模板

<form action="project_create/" method="post">
{{ form.as_p }}
<input type="submit" value="Save" id="dialog-save">
</form>

我想要做的就是保持对话框中的所有活动,即无效的表单条目将在对话框中弹出验证消息。如果表单有效,我希望关闭对话框并返回到调用对话框的页面。我搞乱了form_valid以试图避免不得不遵循重定向,但无济于事。我最终在一个空白页面上,其url等于表单action属性中传递的url。我想避免在提交按钮的jquery中添加一个监听器来处理js中的表单验证。我看过很多帖子建议在js端进行验证,然后将数据传递到django进行保存。我想用django进行验证和保存。

如果我能弄清楚如何做到这一点,我确定可以添加一个监听器来破坏成功表单提交的对话框,但我想使用django进行验证,jquery仅用于演示。有什么提示吗?

1 个答案:

答案 0 :(得分:0)

您必须通过AJAX提交表单,然后用HTTP响应替换对话框的内容。例如:

$(document).on('click', '#dialog-save', function(event) {
    event.preventDefault();
    var $form = $(this).closest('form');
    $.ajax({
        url: $form.prop('action'),
        type: 'POST',
        data: $form.serialize()
    }).done(function (data) {
        $form.replaceWith(data);
    });
};