简体   繁体   中英

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

查看request.resolver_match ,它应该具有您所需要的:

request.resolver_match.kwargs["year"]

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'])
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM