[Django]-How to see if a view function exists based on a url

4👍

The opposite of redirect is resolve [Django-doc] in the django.urls module:

The resolve() function can be used for resolving URL paths to the
corresponding view functions. It has the following signature:

resolve(path, urlconf=None)

path is the URL path you want to resolve. As with reverse(), you
don’t need to worry about the urlconf parameter. The function
returns a ResolverMatch object that allows you to access various
metadata about the resolved URL.

For example:

>>> from django.urls import resolve
>>> resolve('/admin/')
ResolverMatch(func=django.contrib.admin.sites.index, args=(), kwargs={}, url_name=index, app_names=['admin'], namespaces=['admin'])

This thus returns a ResolverMatch that contains the “view” function that will be called together with positional and named parameters, and information about the namespace, name of the app(s), etc.

For URLs that can not be resolved, it will raise a django.urls.exceptions.Resolver404 error.

Note that the querystring is not part of the path. You can extract the path with:

>>> from urllib.parse import urlparse
>>> urlparse('/login/?next=a')
ParseResult(scheme='', netloc='', path='/login/', params='', query='next=a', fragment='')

So only the path='...' part (can be obtained by fetching the .path attribute) will determine the view function, the querystring is passed to the view as a dictionary-like object with request.GET.

Leave a comment