首页 > 解决方案 > Django AJAX删除deleteView中的对象

问题描述

再会。

我试图通过删除对象来了解如何使用 ajax。

主要问题,我不明白如何在AJAX调用中将 slug 参数传递给 url。

path('posts/<slug:slug>/delete/', DeletePost.as_view(), name='delete_post')

class DeletePost(CsrfExemptMixin, DeleteView):
    queryset = Post.objects.all()

    def get_object(self, queryset=None):
        obj = super(DeletePost, self).get_object()
        profile = Profile.objects.get(user_id__exact=self.request.user.id)
        if obj.profile_id != profile.id:
            raise Http404
        return obj

    def delete(self, request, *args, **kwargs):
        self.get_object().delete()
        payload = {'delete': 'ok'}
        return JsonResponse(payload)

我还想了解,功能是否正确?我已经在没有 json 的情况下进行了测试并get_object返回了正确的对象。

  {% for post in user_posts %}
                            <tr id="post_table">
                                <th scope="row">
                                    <input type="checkbox" aria-label="Checkbox" style="display: none">
                                </th>
                                <td class="tm-product-name"><a href="{% url 'post:edit_post' post.slug %}">{{ post.title }}</a></td>
                                    <td class="text-center">145</td>
                                    <td class="text-center">{{ post.total_likes }}</td>
                                    <td>{{ post.created_at }}</td>
                                    <td><button class="delete-icon" onclick='deletePost({{ post.slug }})'>btn</button></td>
                                    {#<td><i  class="fas fa-trash-alt tm-trash-icon delete-icon" id="{{ post.id }}"></i></td>#}
                                    <td>
                                    {#<form method="post" action="{% url 'post:delete_post' post.slug %}" id="delete">#}
                                        {#{% csrf_token %}#}
                                        {#<i  class="fas fa-trash-alt tm-trash-icon"></i>#}
                                    {#</form>#}
                                    </td>
                            </tr>
                        {% endfor %}


<script>
        function deletePost(slug) {
            let action = confirm('Are you sure you want to delete this post?');
            if (action !== false) {
                $.ajax({
                    method: 'POST',
                    url: '{% url 'post:delete_post'%}',
                    success: function (data) {
                        if (data.delete()) {
                            $('#post_table').remove()
                        }
                    }
                });
            }
        }

    </script>

显然这是error我目前拥有的。

Reverse for 'delete_post' with no arguments not found. 1 pattern(s) tried: ['posts/(?P<slug>[-a-zA-Z0-9_]+)/delete/$']

从技术上讲,我只需要一个ping正确DeleteView url的正确的,slug是否需要解析?jsonDeleteView

标签: djangoajaxdjango-class-based-views

解决方案


总之找到了解决办法。

将我的更改view

class DeletePost(CsrfExemptMixin, SingleObjectMixin, View):
    model = Post

    def post(self, *args, **kwargs):
        self.object = self.get_object()
        self.object.delete()
        data = {'success': 'OK'}
        return JsonResponse(data) 

并修改了ajax request

var slug = document.getElementById('delete-icon').getAttribute('data-id');
        function deletePost() {
            let action = confirm('Are you sure you want to delete this post?');

            let url = '/posts/' + slug + '/delete/';
            if (action != false) {
                $.ajax({
                    method: 'POST',
                    url: url,
                    dataType: 'json',
                    success: function (data) {
                        $('#post_table').remove()
                    }
                });
            }
        }

推荐阅读