Python Django:使用基于类的视图在 POST 方法后重定向到同一页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39560175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django: Redirect to same page after POST method using class based views
提问by user298519
I'm making a Django app that keeps track of tv show episodes. This is for a page on a certain Show instance. When a user clicks to add/subtract a season, I want the page to redirect them to the same detail view, right now I have it on the index that shows the list of all Show instances.
我正在制作一个跟踪电视节目剧集的 Django 应用程序。这是针对某个 Show 实例上的页面。当用户单击以添加/减去一个季节时,我希望页面将它们重定向到相同的详细信息视图,现在我将它放在显示所有 Show 实例列表的索引上。
show-detail.html
显示详细信息.html
<form action="{% url 'show:addseason' show=show %}" method="post">
{% csrf_token %}
<button class="btn btn-default" type="submit">+</button>
</form>
<form action="{% url 'show:subtractseason' show=show %}" method="post">
{% csrf_token %}
<button class="btn btn-default" type="submit">-</button>
</form>
views.py
视图.py
class ShowDetail(DetailView):
model = Show
slug_field = "title"
slug_url_kwarg = "show"
template_name = 'show/show-detail.html'
class AddSeason(UpdateView):
model = Show
slug_field = 'title'
slug_url_kwarg = 'show'
fields = []
def form_valid(self, form):
instance = form.save(commit=False)
instance.season += 1
instance.save()
return redirect('show:index')
class SubtractSeason(UpdateView):
model = Show
slug_field = 'title'
slug_url_kwarg = 'show'
fields = []
def form_valid(self, form):
instance = form.save(commit=False)
if (instance.season >= 0):
instance.season -= 1
else:
instance.season = 0
instance.save()
return redirect('show:index')
urls.py
网址.py
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^about/$', views.AboutView.as_view(), name='about'),
# form to add show
url(r'^add/$', views.ShowCreate.as_view(), name='show-add'),
# edit show
#url(r'^(?P<show>[\w ]+)/edit/$', views.ShowUpdate.as_view(), name='show-update'),
# delete show
url(r'^(?P<show>[\w ]+)/delete/$', views.ShowDelete.as_view(), name='show-delete'),
# signup
url(r'^register/$', views.UserFormView.as_view(), name='register'),
# login
url(r'^login/$', views.LoginView.as_view(), name='login'),
# logout
url(r'^logout/$', views.LogoutView.as_view(), name='logout'),
url(r'^error/$', views.ErrorView.as_view(), name='error'),
url(r'^(?P<show>[\w ]+)/$', views.ShowDetail.as_view(), name='show-detail'),
url(r'^(?P<show>[\w ]+)/addseason/$', views.AddSeason.as_view(), name='addseason'),
url(r'^(?P<show>[\w ]+)/subtractseason/$', views.SubtractSeason.as_view(), name='subtractseason'),
url(r'^(?P<show>[\w ]+)/addepisode/$', views.AddEpisode.as_view(), name='addepisode'),
url(r'^(?P<show>[\w ]+)/subtractepisode/$', views.SubtractEpisode.as_view(), name='subtractepisode'),
I get an error when I try
我尝试时出错
return redirect('show:detail')
This is the error
这是错误
NoReverseMatch at /Daredevil/addseason/
Reverse for 'detail' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
回答by Dmitriy Sintsov
For CBV:
对于 CBV:
from django.http import HttpResponseRedirect
return HttpResponseRedirect(self.request.path_info)
For function view:
对于函数视图:
from django.http import HttpResponseRedirect
return HttpResponseRedirect(request.path_info)
回答by David Lam
to redirect to the same page(e.g. an http GET) after a POST, I like...
在 POST 后重定向到同一页面(例如 http GET),我喜欢...
return HttpResponseRedirect("") # from django.http import HttpResponseRedirect
it also avoids hardcoding the show:detail
route name, and is a lil' clearer intention wise (for me at least!)
它还避免了对show:detail
路线名称进行硬编码,并且是一个更清晰的意图(至少对我而言!)
回答by Fatih K?l??
To solve this just add redirect(request.META.get('HTTP_REFERER', 'redirect_if_referer_not_found'))
. It gets HTTP referrer from the request data and if it does not exist it will redirect you to redirect_if_referer_not_found
要解决这个问题,只需添加redirect(request.META.get('HTTP_REFERER', 'redirect_if_referer_not_found'))
. 它从请求数据中获取 HTTP 引用,如果它不存在,它会将您重定向到redirect_if_referer_not_found
So this looks like...
所以这看起来像...
return redirect(request.META.get('HTTP_REFERER', 'redirect_if_referer_not_found'))
回答by James Hiew
I am guessing you need to provide a kwarg to identify the show when you redirect, although I can't see the code for your DetailView
I would assume the kwarg is called either pk
or possibly show
going from the convention you've used in AddSeason
and SubtractSeason
. Try:
我猜你需要提供一个 kwarg 来识别你重定向时的节目,虽然我看不到你的代码DetailView
我会假设 kwarg 被调用pk
或者可能show
来自你在AddSeason
and 中使用的约定SubtractSeason
。尝试:
redirect('show:detail', kwargs={'show': instance.pk})
EDIT:the name of the detail url is 'show-detail'
, so the scoped viewname would be 'show:show-detail'
(if it is in the show
namespace like the other urls). I still think it would need a kwarg though, try:
编辑:详细 url 的名称是'show-detail'
,因此范围视图名称将是'show:show-detail'
(如果它show
像其他 url 一样位于命名空间中)。我仍然认为它需要一个 kwarg,尝试:
redirect('show:show-detail', kwargs={'show': instance.pk})