获取请求中的URL视图名称的Django方法是什么?

huangapple go评论62阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年6月9日 00:12:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76433838.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定