Check if the url matches the pattern

Is it possible to check in the pattern that some URL matches any pattern from the URLs?

+5
source share
4 answers

This is what you would normally want to do in the views.py file using reverse () for named URLs with known arguments or resolve () for paths.

If you really need this functionality in a template, here is a hacky solution:

@register.simple_tag
def urlpath_exists(name):
    """Returns True for successful resolves()'s."""
    try:
        return bool(resolve(path))
    except Resolver404:
        return False

Note : this does not guarantee that the URL is valid, just match the pattern.

+6
source

"" url, , URL.

{% url path.to.view as the_url %}
{% if the_url %}
  <a href="{{ the_url }}">Link to optional stuff</a>
{% endif %}

"as", .

+6

Suppose your project name is fictitious. Then,

from dummy.urls import urlpatterns
def find_url(url):
  for e in urlpatterns:
    if e.regex.match(url):
      print 'found!'  #or do whatever you want
      return          #then exit the procedure.
  print 'not found!'
+1
source

I assume that there is no simple method for this. So I wrote a simple templatetag that takes the url name and calls the inverse method for it and puts reverse in try..except:

try:
    result = reverse(url)
except:
    result = None
return result
0
source

All Articles