Alex Grs
Alex Grs

Reputation: 3301

Accessing URL parameter from context_processor

Let's say we have the following URL:

urlpatterns = patterns('',
    ...
    url(r'^articles/(?P<year>\d{4})/$', 'news.views.year_archive'),
) 

I want to create my own context_processing which will process actions based on the parameter. My issue here, is that I really don't know how to access the parameter...

It is easy to access other GET parameter but for the one embedded in the URL i'm quite stuck.

def year_processor(request):
    # How do i access year from the request object???
    do_some_stuff(year)
    return result

Upvotes: 1

Views: 107

Answers (2)

pancakes
pancakes

Reputation: 712

You may try django.core.urlresolvers.resolve where you can find more information (eg. url_name) about url that being processed:

from django.core.urlresolvers import resolve

def year_processor(request):
    func, args, kwargs = resolve(request.path)

    if 'year' in kwargs:
        do_some_stuff(kwargs['year'])
    ...

Upvotes: 2

Thomas Orozco
Thomas Orozco

Reputation: 55199

Look at request.resolver_match, this should have what you need:

request.resolver_match.kwargs["year"]

Upvotes: 2

Related Questions