django - jquery ajax/django - 在 Bootstrap 模式中显示表单,并在验证不成功时重新显示

标签 django jquery twitter-bootstrap

我的用例是:

a) 在 Bootstrap 模式中呈现通过 ajax 加载的表单,fancy overlay effect stuff.. 。我关注了这些instructions .

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

b) 将此表单提交回我的 Django 应用程序,尝试验证它,如果未验证,则重新显示带有精美 Bootstrap 模式中错误的表单。

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

注意:我没有包含该 View ,因为它没有什么特别的作用。仅实例化和验证表单。

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

我的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>

.js 用于加载表单 + 显示 Bootstrap 模式 + 将表单绑定(bind)到 .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>

从 View 返回的 itemForm 如下所示:

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

加载并显示模式工作正常。 但现在到了第二部分,它没有按预期工作。问题如下。如果表单未验证, View 将返回该表单。返回的表单应再次显示在 Bootstrap 模式中。但结果是浏览器中仅呈现表单,其他所有内容都丢失了。没有CSS,没有表格,只有表单。相当丑陋..因此我没有实现更新ajax_form_modal_result_div。谁能帮我解决我做错了什么..!?

该 View 还返回 js 函数“submitItemModalFormBind”,该函数可防止表单默认行为并通过 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> 

最佳答案

找到了一种工作方法(基于此 solution - 并通过处理无效表单来增强它)并将其发布给任何也想在 django 中使用令人惊叹的美丽 Bootstrap 模式的人。上面代码的主要问题是我没有正确禁用提交按钮的默认行为,并且加载附加 js 的方法不是一个好主意。所以我改变了策略。

在 documentReady 或 ajaxStop 事件上,将超链接的单击事件绑定(bind)到 modalConnect 函数。请注意,如果您有某种 ajax 可以更新表的内容(我有),则只需要 ajaxStop 函数:

<script type="text/javascript">
    $(document).ready(function() {
        modalConnect();
    });
</script>

<script type="text/javascript">
$( document ).ajaxStop( function() {
    modalConnect();
});
</script>

modalConnect 函数加载我们想要在模态中呈现的表单和 formUpdateURLDiv:

<script type="text/javascript">
    function modalConnect()
        {
            //unbind the click event. If not done we will end up with multiple click event bindings, since binding is done after each ajax call.
            $(".editItem").unbind('click');
            //bind the click event
            $(".editItem").click(function(ev) { // for each edit item <a>
                ev.preventDefault(); // prevent navigation
                var url = this.href; //get the href from the <a> element
                $.get(url, function(results){
                  //get the form
                  var itemForm = $("#ajax_form_modal_result", results);
                  //get the update URL
                  var formUpdateURLDiv = $("#formUpdateURL", results);
                  //get the inner html of the div
                  var formUpdateURL = formUpdateURLDiv.html();
                  //update the dom with the received form
                  $('#itemFormModal').html(itemForm);
                  //show the bootstrap modal
                  $("#itemFormModal").modal('show');
                  $(document).ready(function () {
                     //bind the form to an ajax call. ajax call will be set to the received update url
                     submitItemModalFormBind(formUpdateURL);
                  });
                }, "html");
                return false; // prevent the click propagation
            })
        }
</script>

formUpdateURL 包含服务器生成的 URL(请参阅下面包含的 View ),加载的表单必须向该 URL 进行表单提交调用。我们使用此 url 来“初始化”submitItemModalFormBind 函数:

<script type="text/javascript">
       function submitItemModalFormBind(url){
         //bind the form. prevent default behavior and submit form via ajax instead
         $('#ajax_form_modal_result').submit(function(ev){
             $.ajax({
                type: "POST",
                url: url,
                data: $(this).serialize(),
                success:function(response, textStatus, jqXHR){
                     var form = $("#ajax_form_modal_result_div", response);
                     //form is returned if it is not valid. update modal with returned form
                     //change this "if" to check for a specific return code which should be set in the view
                     if (form.html()) {
                        console.log('Form was invalid and was returned');
                        //update modal div
                         $('#ajax_form_modal_result_div').html(form);
                         $("#itemFormModal").modal('show');
                      }
                      //form is not returned if form submission succeeded
                      else{
                        //update the entire document with the response received since we received a entire success page and we want to reload the entire page
                        document.open();
                        document.write(response);
                        document.close();
                        //sort by modified date descending

                        //var notificationDiv = $("#notification", response);
                        //$('#notification').html(notificationDiv.html());
                        console.log('Form was valid and was not returned');
                        $("#itemFormModal").modal('hide');
                        }
                },
                error: function (request, status, error) {
                            var div = $("ajax_form_modal_result_div", request.responseText);
                            $('#ajax_form_modal_result_div').html(div);
                            //implement proper error handling
                            console.log("failure");
                            console.log(request.responseText);
                        }
                    });
                    return false;
                });
              }
</script>

..要了解服务器上发生的情况,请参阅下面处理逻辑的 View :

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),
        )

..表单模板已包含在我的问题中:ajax_form_modal_result_div,您只需要提供 formUpdateURL。我是通过模板完成的,现在我写这篇文章似乎很奇怪。可以通过 View 上下文轻松提供。

瞧 - 带有 Bootstrap Modals 的 Django 表单!为您的用户界面增添趣味!

我希望这可以帮助有人解决类似的问题。

关于django - jquery ajax/django - 在 Bootstrap 模式中显示表单,并在验证不成功时重新显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11944887/

相关文章:

django - 将 Django 过滤器集应用于带注释的查询集?

javascript - 通过RequireJS加载本地jQuery、jQuery UI等文件

javascript - 如何检查我点击了 Bootstrap 模式打开的位置

python - Django 测试 : TransactionManagementError: You can't execute queries until the end of the 'atomic' block

Django - 对两个不同的域名使用不同的 views.py?

django - 如何在Django ORM中实现SUMaggregate()+distinct(fields)

当用户滚动到该 div 时,JQuery 淡入该 div

javascript - 单击菜单选项时如何将导航栏推到顶部?

css - Twitter Bootstrap 2 流体布局应适合屏幕(+ 可滚动区域)

JavaScript 改变 HTML 元素的类