Django - 在表单提交时重新加载div

时间:2017-03-17 09:37:37

标签: ajax django

我正在尝试在提交表单时刷新django应用程序中的某个div。

的index.html

<div class="col-md-8" id="notesColumn">
  {% crispy note_form %}
  {% include 'item/item_notes.html' %}
</div>

item_notes.html

<div class="panel-group panel-group-simple m-b-0" id="notesList" aria-multiselectable="true" role="tablist">
    {% for note in object.itemnote_set.all reversed %}
        <div class="panel">
            <div class="panel-heading" id="noteHeading{{ forloop.counter }}" role="tab">
                <a class="panel-title collapsed" data-parent="#notesList"
                   data-toggle="collapse" href="#noteCollapse{{ forloop.counter }}"
                   aria-controls="noteCollapse{{ forloop.counter }}" aria-expanded="false">
                    <span class="tag tag-default">{{ note.owner.first_name }}</span>
                    {{ note.get_action_display|upper }}
                    <small class="panel-actions">{{ note.date_added }}</small>
                </a>
            </div>
            <div class="panel-collapse collapse" id="noteCollapse{{ forloop.counter }}"
                 aria-labelledby="noteHeading{{ forloop.counter }}" role="tabpanel" aria-expanded="false"
                 style="height: 0px;">
                <div class="panel-body">
                    {{ note.content }}
                </div>
            </div>
        </div>
    {% endfor %}
</div>

app.js(包含在index.html中)

$(document).ready(function () {
  $("#notesTab form").submit(function(event){
      event.preventDefault();

  $('#notesList').remove();

  $.ajax({
    url: "{% url item_notes %}",
    success: function(data){
      $('#notesColumn').html('data');
    }
  })
})

views.py

def item_notes(request):
  return render_to_response(request, 'candidate/candidate_notes.html')

urls.py

url(r'item/profile/(?P<pk>[0-9]+)/$', views.ItemProfile.as_view(), name='item_profile'),
  url(r'item/notes', views.item_notes, name='item_notes'),

我从chrome获得的错误是:

http://127.0.0.1:8000/crm/item/profile/45/%7B%%20url%20item_notes%20%%7D 
Failed to load resource: the server responded with a status of 404 (Not Found)

2 个答案:

答案 0 :(得分:3)

您不能在外部JS文件中使用Django模板标记 - Django不会解析该文件,这就是为什么您可以看到文字标记被附加到您的Ajax URL。

您需要在模板本身的内联脚本中将该值设置为全局JS var。

答案 1 :(得分:0)

首先,尝试使用绝对网址来查看是否是导致错误的网址:

  $.ajax({
    url: "item/notes",
    success: function(data){
      $('#notesColumn').html('data');
    }
  })

其次,为什么要获取笔记网址? Aren你没有使用&#39; item_profile&#39;为了那个原因?在这种情况下,请尝试获取该URL:

  $.ajax({
    url: "item/profile/" + "{{ object.pk }}",
    success: function(data){
      $('#notesColumn').html('data');
    }
  })

第三,检查你的JS代码,你错过了$("#notesTab form").submit的结束括号。

第四,尝试转义URL。我不确定在JS中使用哪种方法,但由于未转义的代码,我多次遇到这个问题。

这些只是我头脑中的一些提示。希望有所帮助。

相关问题