For dynamic urls, you can also use the request.resolver_match
attribute (docs):
HttpRequest.resolver_match
An instance of ResolverMatch representing the resolved URL. This attribute is only set after URL resolving took place, which means it’s available in all views but not in middleware which are executed before URL resolving takes place (you can use it in process_view() though).
The returned ResolverMatch
object has many useful attributes, such as the view_name
attribute, which returns the same name you would have passed to the url
templatetag to generate the current url.
view_name
The name of the view that matches the URL, including the namespace if there is one.
See the docs for this and other attributes.
Applying this to the example from @nimasmi's answer, you would get:
{% if request.resolver_match.view_name == 'show_user_page' %}something{% endif %}
where your urls.py contains something like:
(r'^myapp/user/(?P<user>\d+)/$', 'show_user_page'),
Note that when you use URL namespaces, view_name
will return the namespace qualified url/view name, e.g. app:urlname
.
Compared to the answer by @nimasmi, this simplifies the template code a bit, by not needing the separate {% url %}
tag to generate the url to compare with. This is especially true when you do not need to compare view parameters, just the view name. If you do need to compare parameters in the url, you can easily use the ResolverMatch.args
and kwargs
attributes, though.