16

What's the best way to add a "cancel" button to a generic class-based view in Django?

In the example below, I would like the cancel button to take you to success_url without deleting the object. I have tried adding a button <input type="submit" name="cancel" value="Cancel" /> to the template. I can detect if this button was pressed by overriding the post method of the AuthorDelete class, but I can't work out how to redirect from there.

Example myapp/views.py:

from django.views.generic.edit import DeleteView
from django.core.urlresolvers import reverse_lazy
from myapp.models import Author

class AuthorDelete(DeleteView):
    model = Author
    success_url = reverse_lazy('author-list')

    def post(self, request, *args, **kwargs):
        if request.POST["cancel"]:
            return ### return what? Can I redirect from here?
        else:
            return super(AuthorDelete, self).post(request, *args, **kwargs)

Example myapp/author_confirm_delete.html:

<form action="" method="post">{% csrf_token %}
    <p>Are you sure you want to delete "{{ object }}"?</p>
    <input type="submit" value="Confirm" />
    <input type="submit" name="cancel" value="Cancel" /> 
</form>

(Examples adapted from the docs)

4

5 回答 5

19

您覆盖该post方法并检查是否按下取消按钮的方法是可以的。HttpResponseRedirect您可以通过返回实例来重定向。

from django.http import HttpResponseRedirect

class AuthorDelete(DeleteView):
    model = Author
    success_url = reverse_lazy('author-list')

    def post(self, request, *args, **kwargs):
        if "cancel" in request.POST:
            url = self.get_success_url()
            return HttpResponseRedirect(url)
        else:
            return super(AuthorDelete, self).post(request, *args, **kwargs)

我以前get_success_url()是通用的,它的默认实现是返回self.success_url

于 2013-07-16T14:13:04.267 回答
14

为什么不简单地将“取消”链接放置到success_url按钮而不是按钮?您始终可以使用 CSS 对其进行样式设置,使其看起来像一个按钮。

这样做的好处是不使用 POST 表单进行简单的重定向,这会混淆搜索引擎并破坏 Web 模型。此外,您不需要修改 Python 代码。

于 2013-07-17T10:25:54.487 回答
10

如果使用 CBV,您可以view直接从模板访问

<a href="{{ view.get_success_url }}" class="btn btn-default">Cancel</a>

注意:如果它已被子类化,您应该通过 getter 访问它。

这在ContextMixin 文档中有说明

所有基于类的通用视图的模板上下文都包含一个view 指向 View 实例的变量。

于 2017-05-25T13:39:49.883 回答
1

拥有按钮类型的元素,将不会发送 POST 请求。因此,您可以使用它来执行如下 http 重定向:

<button type="button" onclick="location.href='{{ BASE_URL }}replace-with-url-to-redirect-to/'">Cancel</button>
于 2021-05-17T04:24:28.397 回答
-1

你甚至需要get_success_url,为什么不直接使用:

取消

并转到您想要的任何其他网址?

于 2019-02-12T15:40:53.780 回答