使用ajax和django删除for循环中的项

时间:2015-07-28 01:39:43

标签: javascript jquery ajax django

尝试使用bootstrap×在点击和淡出时删除帖子/评论。我写了一些代码,但它不起作用。我觉得我错过了这么简单的事情。任何指导或帮助将受到高度赞赏。 urls.py

url(r'^delete/(?P<pk>\d+)/$', views.delete, name='delete'),

views.py

@login_required
def delete(request, pk):
    warn = get_object_or_404(Warning, pk=pk)
    fop = get_object_or_404(Followers, pk=warn.person.pk)
    warn.delete()
    return redirect('yardsale.views.follower_warnings', pk=fop.pk)

模板

{% for warns in warn.warnings.all %}
                <div class="warning-list col-md-4">
                {# <a href="{% url 'delete' pk=warns.pk %}"> #}
                <button type="button" class="close">&times;</button>
                {# </a> #}
                <div class="publish-date"><strong>Warned:</strong>  {{ warns.publish_date }}</div>
                <div class="posted-by"><strong>Warned By: </strong> {{ warns.author }}</div>
            <div class="warningtype"><strong>Warning Type: </strong>{{ warns.WarningType }}</div>
            <div class="description">
                <strong>Description:</strong> {{ warns.descript }}
            </div>
            {% endfor %}

main.js

$(".close").click(function () {
  if (confirm("Are you sure you want to delete this?")){
$.ajax({
  type: "DELETE",
  url: "{% url 'delete' pk=warns.pk %}",
  beforeSend: function(xhr) {
    xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
  }
  success: function() {
    var close=$(this).parent();
    close.fadeOut(1000);
     });
    }
   })
  }
 });

1 个答案:

答案 0 :(得分:0)

main.js如下。

$(".close").click(function () {
  var close=$(this).parent();
  if (confirm("Are you sure you want to delete this?")){
    $.ajax({
      type: "DELETE",
      url: $(this).data('url'),
      beforeSend: function(xhr) {
        xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
      },
      success: function() {
        close.fadeOut(1000);
      }
    });
  }
});