[英]Django class based generic view redirect
Consider the following:考虑以下:
urls.py:网址.py:
urlpatterns = patterns('',
('^test/$', ClassView.as_view()),
)
views.py:视图.py:
class ClassView(View):
def get(self, request):
return HttpResponse("test")
def post(self, request):
# do something
return redirect(ClassView.get(request)) # What should I do to redirect to a class here without specifying the path?
I want to redirect to ClassView's get function (/test/), but when I try the above I get:我想重定向到 ClassView 的 get 函数 (/test/),但是当我尝试上述操作时,我得到:
NoReverseMatch at /test/
So it obviously finds the URL but says that there's no match?所以它显然找到了 URL 但说没有匹配?
You should just name your urlpattern and redirect to that, that would be the most Django-ey way to do it.你应该只命名你的 urlpattern 并重定向到那个,这将是最 Django-ey 的方式。
It's not documented (so not guaranteed to work in future Django versions) but the redirect
shortcut method can take a view function, so you can almost do redirect(ClassView.as_view())
...I say almost because this doesn't actually work - every time you call as_view()
you get a new view function returned, so redirect
doesn't recognise that as the same view as in your urlconf.它没有记录(所以不能保证在未来的 Django 版本中工作)但是
redirect
快捷方法可以采用视图函数,所以你几乎可以做redirect(ClassView.as_view())
......我说几乎是因为这实际上并没有工作 - 每次调用as_view()
,都会返回一个新的视图函数,因此redirect
不会将其识别为与 urlconf 中的视图相同。
So to do what you want, you'd have to update your urlconf like so:所以要做你想做的事,你必须像这样更新你的 urlconf:
from .views import test_view
urlpatterns = patterns('',
('^test/$', test_view),
)
And in your views.py在你的 views.py 中
class ClassView(View):
def get(self, request):
return HttpResponse("test")
def post(self, request):
# do something
return redirect(test_view)
test_view = ClassView.as_view()
But I still think you should do it the other way:但我仍然认为你应该用另一种方式来做:
urlpatterns = patterns('',
url('^test/$', ClassView.as_view(), name="test"),
)
. .
class ClassView(View):
def get(self, request):
return HttpResponse("test")
def post(self, request):
# do something
return redirect("test")
可能您应该将名称设置为您的 urlpattern 并重定向到该名称?
def post(self, request, *args, **kwargs):
return HttpResponseRedirect(request.path)
This will redirect to the same URL as your post()
, and then get handled by your get()
.这将重定向到与您的
post()
相同的 URL,然后由您的get()
处理。
Try return self.get()
.尝试返回
self.get()
。 I didn't test.我没有测试。 But as its a python code it should work.
但作为一个 python 代码,它应该可以工作。 Use this if you only want to execute the statements.
如果您只想执行语句,请使用此选项。 This will not return any HTTP 302 status I think.
我认为这不会返回任何 HTTP 302 状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.