Suppose, we have a url path:
path('something/<int:some_param>/test/', views.some_view)
When a user hits this url, django
makes an instance of HttpRequest
, that will be passed to the some_view
view. Is there a way to get the some_param
url parameter from the request object outside the some_view
code? (for instance, to do some processing that depends on some_param
in a custom middleware).
One possible solution is to parse the HttpRequest.path
attribute, but is there any prebuilt way to do this?
The one possible solution here is to use the resolve
function from django.urls
module. It is extremely uselful if you want to access the URL parameters from URL path that is related to a HttpRequest
object outside a view function. For example, get the URL params and process them in the custom middleware or other parts of your code.
Example:
from django.urls import resolve
...
func, args, kwargs = resolve(some_request.path)