django url变量获取参数

时间:2015-10-05 05:03:26

标签: django django-urls

我的urls.py文件的一部分如下:

urlpatterns = patterns('',
    url(r'^$', DetailHomePublic),
    url(r'^demo/$', TemplateView.as_view(template_name='public/demo.html')),
    url(r'^privacy/$', TemplateView.as_view(template_name='public/privacy.html')),
    url(r'^terms/$', TemplateView.as_view(template_name='public/terms.html')),
    url(r'^login/$', Login),
    url(r'^logout/$', Logout),
    url(r'^lost_password/$', LostPassword),
    url(r'^register/$', Register),
)

我已经完成了一个中间件,它可以捕获一个名为language的参数。它用于改变网站的语言。

class SetLanguageMiddleware:
"""
Middleware which changes the language if the GET variable named language has been set with a valid language referenced on the settings.py file
"""
def process_request(self, request):
    from django.utils import translation
    from django.conf import settings
    from django.utils.translation import LANGUAGE_SESSION_KEY



    if 'language' in request.GET:
        language = request.GET['language']
        #check if the language is defined in the settings.LANGUAGES global settings

        if any(language in code for code in settings.LANGUAGES):
            #set the given language in the session and active it for the current page too
            request.session[LANGUAGE_SESSION_KEY] = language
            translation.activate(request.session[LANGUAGE_SESSION_KEY])

现在,仅针对此给定页面,我想添加语言前缀以提供多语言网站。

是否可以在urls文件中捕获前缀并将其添加到GET参数中,以获得类似的内容:

urlpatterns = patterns('',
    url(r'^(?P<language>[a-z]{3})$', DetailHomePublic),
    url(r'^(?P<language>[a-z]{3})demo/$', TemplateView.as_view(template_name='public/demo.html')),
)
...

谢谢

0 个答案:

没有答案