deleteView中的Django AJAX删除对象

问题描述 投票:0回答:1

早安。

我试图通过删除对象来了解如何使用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,是否需要解析json中的DeleteView

django ajax django-class-based-views
1个回答
0
投票

无论如何都找到了解决方法。

将我的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()
                    }
                });
            }
        }
© www.soinside.com 2019 - 2024. All rights reserved.