jquery ajax/django-以引导模式呈现表单,并在验证未成功时重新显示

jquery ajax/django-以引导模式呈现表单,并在验证未成功时重新显示,django,jquery,twitter-bootstrap,Django,Jquery,Twitter Bootstrap,我的用例是: a) 以引导模式呈现通过ajax加载的表单。我跟着这些 这个很好用。(见下面的代码) b) 将此表单提交回我的Django应用程序,尝试验证它,如果它未验证,请在奇特的引导模式中重新显示包含错误的表单 我可以通过ajax重新加载表单,但我无法在模式中再次表示它 注意:我没有包括视图,因为它没有任何特殊功能。仅实例化和验证表单 下面有很多内容需要阅读,所以如果您认为用例听起来很有趣,请继续 My taskList.html如下所示: <table id="listItemTab

我的用例是:

a) 以引导模式呈现通过ajax加载的表单。我跟着这些

这个很好用。(见下面的代码)

b) 将此表单提交回我的Django应用程序,尝试验证它,如果它未验证,请在奇特的引导模式中重新显示包含错误的表单

我可以通过ajax重新加载表单,但我无法在模式中再次表示它

注意:我没有包括视图,因为它没有任何特殊功能。仅实例化和验证表单

下面有很多内容需要阅读,所以如果您认为用例听起来很有趣,请继续

My taskList.html如下所示:

<table id="listItemTable" class="table table-bordered">
        <thead>
            <tr>
                <th>Name</th>
                <th>Edit</th>
            </tr>
        </thead>
    <tbody>
        <tr>
            <td>Task 1</td>
            <td><a class="editItem" href="/update/item/1/">edit</a></td>
        </tr>
    </tbody>
</table>

<div class="modal hide" id="itemFormModal"></div>
<div id="modalExtraJsPlaceholder"></div>
<form id="#ajax_form_modal_result" class="well" method="post" action="/update/item/{{ item.id }}">
 <div id="ajax_form_modal_result_div">
     <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">×</button>
      <h3>Edit Item</h3>
    </div>
    <div class="modal-body">
         {% csrf_token %}
         {{form.as_p}}
    </div>
    <div class="modal-footer">
         <input class="btn btn-primary" type="submit" value="Save" />
         <input name="cancel" class="btn" type="submit" value="Cancel"/>
     </div>
    </div>
</form>

名称
编辑
任务1
.js加载表单+显示引导模式+将表单绑定到.jquery提交调用:

$(document).ready(function() {
   modalConnect();
});

<script type="text/javascript">
 //connects the modal load for each <a> with class editItem
 //Functionality 1
     //loads an item edit form from the server and replaces the itemFormModal with the form
     //presents the modal with $("#itemFormModal").modal('show');
 //Functionality 2
     //loads some extra js "modalExtraJsHtml"
     //calls the function "submitItemModalFormBind" which has been loaded via "modalExtraJsHtml"

 function modalConnect(){
    $(".editItem").click(function(ev) { // for each edit item <a>
    ev.preventDefault(); // prevent navigation
    url = ($(this)[0].href); //get the href from <a>
    $.get(url, function(results){
       var itemForm = $("#ajax_form_modal_result", results);
       var modalExtraJs = $("#modalExtraJs", results);
       //get the html content
       var modalExtraJsHtml = modalExtraJs.html();
       //update the dom with the received results
        $('#itemFormModal').html(itemForm);        
        $('#modalExtraJsPlaceholder').html(modalExtraJsHtml);
        $("#itemFormModal").modal('show');
        submitItemModalFormBind(); //bind loaded form to ajax call
     }, "html");
     return false; // prevent the click propagation
   })
}
</script>
$(文档).ready(函数(){
modalConnect();
});
//将每个类的模态载荷与editItem连接
//功能1
//从服务器加载项目编辑表单,并用表单替换itemFormModal
//用$(“#itemFormModal”).modal('show')表示模式;
//功能2
//加载一些额外的js“modalExtraJsHtml”
//调用通过“modalExtraJsHtml”加载的函数“submitItemModalFormBind”
函数modalConnect(){
$(“.editItem”)。为每个编辑项单击(函数(ev){//
ev.preventDefault();//防止导航
url=($(this)[0].href);//从中获取href
$.get(url、函数(结果){
var itemForm=$(“#ajax#form_model_result”,results);
var modalExtraJs=$(“modalExtraJs”,结果);
//获取html内容
var modalExtraJsHtml=modalExtraJs.html();
//使用收到的结果更新dom
$('#itemFormModal').html(itemForm);
$('#modalExtraJsPlaceholder').html(modalExtraJsHtml);
$(“#itemFormModal”).modal('show');
submitItemModalFormBind();//将加载的表单绑定到ajax调用
},“html”);
返回false;//防止单击传播
})
}
从视图返回的itemForm如下所示:

<table id="listItemTable" class="table table-bordered">
        <thead>
            <tr>
                <th>Name</th>
                <th>Edit</th>
            </tr>
        </thead>
    <tbody>
        <tr>
            <td>Task 1</td>
            <td><a class="editItem" href="/update/item/1/">edit</a></td>
        </tr>
    </tbody>
</table>

<div class="modal hide" id="itemFormModal"></div>
<div id="modalExtraJsPlaceholder"></div>
<form id="#ajax_form_modal_result" class="well" method="post" action="/update/item/{{ item.id }}">
 <div id="ajax_form_modal_result_div">
     <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">×</button>
      <h3>Edit Item</h3>
    </div>
    <div class="modal-body">
         {% csrf_token %}
         {{form.as_p}}
    </div>
    <div class="modal-footer">
         <input class="btn btn-primary" type="submit" value="Save" />
         <input name="cancel" class="btn" type="submit" value="Cancel"/>
     </div>
    </div>
</form>

×
编辑项
{%csrf_令牌%}
{{form.as_p}}
加载和显示模态效果良好。 但现在是第二部分,它并没有像预期的那样起作用。问题如下。如果表单未验证,视图将返回表单。返回的表单应在引导模式中再次显示。但结果是,浏览器中只显示表单,其他所有内容都将丢失。没有css,没有表格,只有表单。很难看。。因此,我没有更新ajax\u form\u modal\u result\u div。有人能帮我解决我做错了什么吗

该视图还返回js函数“submiteModalFormBind”,该函数阻止表单默认行为,并通过ajax发送表单

<div id="modalExtraJs">
 //ajax bind for update item form visualized via modal
 function submitItemModalFormBind(){
     var url = "{% url updateItem item.pk %}";
     $('#ajax_form_modal_result').submit(function(){
 $.ajax({
    type: "POST",
    url: "{% url updateTask item.pk %}",
    data: $(this).serialize(),
    success:function(response){
        var div = $("ajax_form_modal_result_div", response);
        $('#ajax_form_modal_result_div').html(div);
     },
     error: function (request, status, error) {
         console.log("failure");
         console.log(request.responseText);
     }

           });
          });
        return false;
       }    
</div> 

//通过modal可视化更新项表单的ajax绑定
函数submiteModalFormBind(){
var url=“{%url updateItem.pk%}”;
$('#ajax_form_modal_result')。提交(函数(){
$.ajax({
类型:“POST”,
url:“{%url updateTask item.pk%}”,
数据:$(this).serialize(),
成功:功能(响应){
var div=$(“ajax\u form\u model\u result\u div”,响应);
$('#ajax_form_modal_result_div').html(div);
},
错误:功能(请求、状态、错误){
控制台日志(“故障”);
console.log(request.responseText);
}
});
});
返回false;
}    
找到了一种有效的方法(基于此-并通过处理无效表单对其进行了增强),并将发布给任何想在django中使用漂亮的引导模式的人。上面代码的主要问题是,我没有正确地禁用submit按钮的默认行为,加载其他js的方法也不是一个好主意。所以我改变了策略

在documentReady或ajaxStop事件上,将超链接的click事件绑定到modalConnect函数。请注意,如果您有某种ajax更新表的内容(我有):

…表单模板已经包含在我的问题中:ajax\u form\u modal\u result\u div,您只需提供formUpdateURL。我是通过模板完成的,现在写这篇文章似乎很奇怪。可以通过视图上下文轻松提供

瞧,Django表单和引导模式!为你的用户界面增添趣味


我希望这能帮助别人解决类似的问题

我写了一个简单的AJAX,它帮了我的忙,希望它能帮助我:

$(document).on('submit', 'div.modal-body form', function(e) {
        var form_el = $(this);
        e.preventDefault();
        $.ajax({
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function (xhr, ajaxOptions, thrownError) {
                if ( $(xhr).find('.errorlist').length > 0 ) {
                    form_el.parents('.modal-body').html(xhr);
                } else {
                    form_el.parents('.modal-body').html('<h4>Formulario enviado correctamente</h4>');
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                form_el.parents('.modal-body').html(xhr);
            }
        });
});

嘿,我正在努力理解需要包含formUpdateURL的内容。
class UpdateTaskModalView(LoginRequiredMixin, View):
template = 'list_management/crud/item/update_via_modal.html'

def get_logic(self, request, task_id, **kwargs):
    task = get_object_or_404(Task.objects, pk=task_id)
    task_form = TaskForm(instance=task)
    context = {
               'model_form': task_form,
               'item': task,
    }
    return context

def post_logic(self, request, task_id, **kwargs):
    task = get_object_or_404(Task.objects, pk=task_id)
    task_form = TaskForm(request.POST, instance=task)
    if task_form.is_valid():
        task = task_form.save(commit=False)
        task.modified_by = request.user
        task.save()
        messages.add_message(request, messages.INFO, 'Item "%s" successfully updated' % (task.name))
        return ('redirect', HttpResponseRedirect(reverse('show_list_after_item_update', kwargs={'list_id':task.list.pk, 'item_id':task.pk})))
    context = {
        'model_form' : task_form,
        'list': task.list,
        'item': task,
    }
    return ('context', context)

def get(self, request, task_id, **kwargs):
    context = self.get_logic(request, task_id, **kwargs)
    return render_to_response(
        self.template,
        context,
        context_instance = RequestContext(request),
    )

def post(self, request, task_id, **kwargs):
    post_logic_return = self.post_logic(request, task_id, **kwargs)
    if post_logic_return[0] == 'redirect':
        return post_logic_return[1]
    if post_logic_return[0] == 'context':
        context = post_logic_return[1]
        return render_to_response(
            self.template,
            context,
            context_instance = RequestContext(request),
        )
$(document).on('submit', 'div.modal-body form', function(e) {
        var form_el = $(this);
        e.preventDefault();
        $.ajax({
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function (xhr, ajaxOptions, thrownError) {
                if ( $(xhr).find('.errorlist').length > 0 ) {
                    form_el.parents('.modal-body').html(xhr);
                } else {
                    form_el.parents('.modal-body').html('<h4>Formulario enviado correctamente</h4>');
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                form_el.parents('.modal-body').html(xhr);
            }
        });
});
$('.modal-class').on('click',function(){
    let dataURL = $(this).attr('data-href');
    $('.modal-body').load(dataURL,function(){
        $('#modal_crear').modal({show:true});
    });
});