英文:
Django: how to get a URL view name from a request?
问题
在Django的URL配置中,您可以使用"url视图名称"来辅助各种活动,如重定向。在这个示例的urls.py
文件中可以看到如下(name
参数的部分):
urlpatterns = [
path('', views.home_view, name='home'),
path('search/', views.search_view, name='search'),
....
现在,在我的Django视图函数中,我想要检查当前的request
对象以发现当前请求的URL视图名称。这对于创建一个通用的"handler"函数可能会很有用,该函数可以从多个视图中调用(或者更好的是用于视图装饰器)。
这将允许您的通用功能在POST请求时重定向到当前页面,但要通过redirect()
进行重定向,需要知道要重定向到的"url视图名称"。
如何通过检查当前的request
来找到"url视图名称"?
英文:
In Django url configs, you can use url "view names" to aid various activities like redirects. Seen here in this example urls.py
file (the final name
arguments):
urlpatterns = [
path('', views.home_view, name='home'),
path('search/', views.search_view, name='search'),
....
Now, in my Django view function, I would like to inspect the current request
object to discover the current url "view name" for the current request. This could be useful to create a general-purpose "handler" function that could be called from multiple views (or better yet to use in a view decorator).
This would allow your general purpose function to redirect to the current page on a POST request for example. But to redirect via redirect()
requires knowing the "view name" you want to redirect to.
How can I find the "view name" by inspecting the current request
?
答案1
得分: 1
你可以通过调用resolve()
并传递当前请求路径来获取当前的URL "view name"。这会返回一个包含当前 "view name" 的ResolverMatch
对象。
from django.urls import resolve
def my_view(request):
current_view_name = resolve(request.path).view_name
然后你可以类似这样进行重定向...
return redirect(current_view_name, **kwargs)
英文:
You can discover the current url "view name" by calling resolve()
passing the current request path. That returns a ResolverMatch
object which has a view_name
property containing the current "view name".
from django.urls import resolve
def my_view(request):
current_view_name = resolve(request.path).view_name
then you could redirect similar to…
return redirect(current_view_name, **kwargs)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论