Django DeleteView没有确认模板

jdzmm42g  于 2023-01-14  发布在  Go
关注(0)|答案(6)|浏览(144)

我在一个模板中使用Django DeleteView,并且我创建了一个url & view。是否可以跳过加载_confirm_delete模板的过程,直接发布删除操作。

sz81bmfz

sz81bmfz1#

DeleteView响应POSTGET请求,GET请求显示确认模板,POST删除示例。
您可以发送POST请求,无需确认,表单如下:

<form method="POST" action="{% url "your_delete_url_name" %}">
   {% csrf_token %}<input type="submit" value="DELETE">
</form>

如果你不想有一个链接,而不是形式按钮,使用一些javascript使不可见的形式,这将是提交的链接点击。
使用GET请求进行更新或删除并不是一个好的做法,但如果您确实坚持要使用get方法,可以在类视图中将其快捷方式设置为post,即:

def get(self, *args, **kwargs):
    return self.post(*args, **kwargs)
rhfm7lfc

rhfm7lfc2#

也可以在DeleteView中重新定义get()方法:

class YourDeleteView(DeleteView):

    model = YourModel
    success_url = '<success_url>'

    def get(self, request, *args, **kwargs):
        return self.post(request, *args, **kwargs)

但要小心,确保这不会影响其他功能。

trnvg8h3

trnvg8h33#

是的,只要修改下一个参数,在返回响应中,确保传入的字典是这样的:{ 'next': '/<your_path_here>}/' },请确保在添加next参数之前提交更改。您可能需要更改视图的getpost函数。

brvekthn

brvekthn4#

或者,您只能通过将请求直接路由到类的delete方法来允许HTTP请求方法delete

from django.views.generic import DeleteView
from django.http import HttpResponseForbidden

class PostDeleteView(DeleteView):
    model = Post
    http_method_names = ['delete']

    def dispatch(self, request, *args, **kwargs):
        # safety checks go here ex: is user allowed to delete?
        if request.user.username != kwargs['username']:
            return HttpResponseForbidden()
        else:
            handler = getattr(self, 'delete')
            return handler(request, *args, **kwargs)

    def get_success_url(self):
        username = self.kwargs.get('username')
        success_url = str(reverse_lazy('post:user_home', kwargs={'username': username}))
        return success_url

假设您的URL如下所示:

path('posts/delete/<int:pk>/', PostDeleteView.as_view(), name='post_delete'),

为了清楚地了解为什么这样做,必须分析postdelete方法。

def post(self, request, *args, **kwargs):
    return self.delete(request, *args, **kwargs)

def delete(self, request, *args, **kwargs):
    """
    Call the delete() method on the fetched object and then redirect to the
    success URL.
    """
    self.object = self.get_object()
    success_url = self.get_success_url()
    self.object.delete()
    return HttpResponseRedirect(success_url)

post只调用deletedelete获取对象和成功URL,删除对象,然后重定向到您提供的成功URL。pk_url_kwarg = 'pk'是我在URL中显示<int:pk>部分的原因。

7rfyedvj

7rfyedvj5#

您可以覆盖get()方法,使其行为与delete()方法完全相同:

def get(self, request, *args, **kwargs):
  return self.delete(request, *args, **kwargs)

参见CCBV:https://ccbv.co.uk/projects/Django/4.1/django.views.generic.edit/DeleteView/

fcwjkofz

fcwjkofz6#

你所要做的就是重写删除视图的get_success_url方法,然后它将直接从数据库中删除对象。例如:

class YourView(DeleteView):
    model = YourModel

    def get_success_url(self):
        return reverse('your_redirect_view')

相关问题