简体   繁体   English

从context_processor访问URL参数

[英]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. 我想创建自己的context_processing,它将根据参数处理动作。 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. 访问其他GET参数很容易,但是对于嵌入在URL中的那个我还是很困惑。

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: 您可以尝试django.core.urlresolvers.resolve ,在其中可以找到有关正在处理的url的更多信息(例如url_name ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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