django - 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
是否需要解析?json
DeleteView
解决方案
总之找到了解决办法。
将我的更改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()
}
});
}
}
推荐阅读
- linux - 为 Mattermost 构建 Docker,未找到 /bin/sh dnf
- amazon-web-services - 获取 ENI 并将它们解析为 CloudFormation 中的 IP
- tensorflow - CNN模型突然停止学习,返回空白输出怎么办?
- python - 用漂亮的汤瞄准第三个列表项
- r - 如何使用 Animation 包累积/保留旧帧?
- python - 尽管使用了“字符串替换”和“删除标点符号”,但仍无法从 pandas 文本数据框中删除 '
- python - Convert an input result/string to integer in Python
- android - Android Jsoup doc.select("");
- kdb - Q(kdb)中如何用“IN”查询?
- syntax - 在 Racket 语言中对函数返回进行操作