【发布时间】:2020-03-29 16:15:09
【问题描述】:
美好的一天。
我正在尝试通过删除对象来了解如何使用 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,是否需要在DeleteView 中解析json?
【问题讨论】:
-
我相信你可以从
self.kwargsdict 中得到slug,类似于:`slug = self.kwargs.get('slug')。
标签: django ajax django-class-based-views