Marcos Aguayo
Marcos Aguayo

Reputation: 7170

Get reverse URL name from full path

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

Upvotes: 5

Views: 1945

Answers (2)

almalki
almalki

Reputation: 4775

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}

Upvotes: 1

ndpu
ndpu

Reputation: 22561

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?

Upvotes: 4

Related Questions