reverse in Django

发布时间 2023-03-26 22:30:21作者: ChuckLu

问题

url patterns:

path("rev/abc",views.getUrlNoParam,name="urlNoPara"),
    path("rev2/<data>",views.getUrlArgs,name="UrlArgs"),
    path("rev3/<data>",views.getUrlKWArgs,name="UrlKwargs"),
    path("rev4/",views.getViewUrl)

 

views.py

from django.urls import reverse
def getUrlNoParam(request):
    return HttpResponse("请求的url路径为:"+reverse("urlNoPara"))

def getUrlArgs(request,data):
    return HttpResponse("请求的url路径为:"+reverse("UrlArgs",args=["sadas"]))

def getUrlKWArgs(request,data):
    return HttpResponse("请求的url路径为:"+reverse("UrlKwargs",kwargs={'data':1234}))

def getViewUrl(request):
    return HttpResponse("getUrlKWArgs视图函数的路径为"+reverse(getUrlKWArgs,kwargs={'data':1234}))

 

These URL patterns define four views:

  • getUrlNoParam: handles requests for the path rev/abc and uses reverse("urlNoPara") to generate and return the path rev/abc.
  • getUrlArgs: handles requests for paths like rev2/some_data and uses reverse("UrlArgs", args=["sadas"]) to generate and return the path rev2/sadas.
  • getUrlKWArgs: handles requests for paths like rev3/1234 and uses reverse("UrlKwargs", kwargs={'data': 1234}) to generate and return the path rev3/1234.
  • getViewUrl: handles requests for the path rev4/ and uses reverse(getUrlKWArgs, kwargs={'data':1234}) to generate and return the path rev3/1234.

In each view function, reverse is used to generate a URL path based on the name of the URL pattern associated with the view function.

The args argument is used to pass positional arguments to the URL pattern,

while the kwargs argument is used to pass keyword arguments.

Note that reverse requires the name of the URL pattern, not the view function, as its first argument. In the case of getViewUrl, the name of the URL pattern is obtained by passing the view function getUrlKWArgs as the first argument to reverse.

 

explain the parameters of reverse function in Django

The reverse() function in Django is used to generate URLs based on the name of the view and the arguments passed to it. The function has the following parameters:

  • viewname: The name of the view you want to reverse. This can be a string with the name of the view, or it can be a reference to the actual view function or class.

  • urlconf: (Optional) The URLconf module to use for reversing the URL. This parameter is used when you have multiple URLconfs in your project, and you want to use a specific one for reversing the URL.

  • args: (Optional) A list or tuple of arguments to be passed to the view function. These arguments are used to build the URL.

  • kwargs: (Optional) A dictionary of keyword arguments to be passed to the view function. These arguments are also used to build the URL.

  • current_app: (Optional) The name of the current application. This is used to resolve application namespaced URLs.

The reverse() function returns a string that contains the generated URL.