Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get reverse URL name from full path

Tags:

python

django

Does anyone knows how I can get the URL name from the request.get_full_path()?

For example:

I have this URL in urls.py

url(r'^evaluation-active/$', 'web.evaluation.evaluation', name='evaluation'),

In my context_processor.py:

def is_evaluation(request):
    return {"test":request.get_full_path()}

How can I return "evaluation" instead of "/evaluation-active/"?

Thanks

like image 329
Marcos Aguayo Avatar asked Mar 01 '14 14:03

Marcos Aguayo


2 Answers

From django docs:

HttpRequest.resolver_match

New in Django 1.5. 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 methods which are executed before url resolving takes place (like process_request, you can use process_view instead).

There is url_name attribute in ResolverMatch object:

def is_evaluation(request):
    return {"test": request.resolver_match.url_name}

For django version < 1.5 there is answer here: How to get the current urlname using Django?

like image 198
ndpu Avatar answered Sep 23 '22 21:09

ndpu


If using django 1.5 or higher, use request.resolver_match to get the ResolverMatch object.

def is_evaluation(request):
    return {"test":request.resolver_match.url_name}

if using version before 1.5, then use resolve:

def is_evaluation(request):
    return {"test":resolve(request.path_info).url_name}
like image 24
almalki Avatar answered Sep 23 '22 21:09

almalki