使用i18n_patterns时,如何在没有语言代码的情况下反转url

时间:2014-12-28 21:28:40

标签: django django-i18n

我正在使用i18n_patterns,但我想使用reverse创建指向网页的链接,而网址中没有语言(这样用户将根据Cookie和标头等重定向)。

我试过了

from django.utils.translation import activate, deactivate, get_language
current_lang = get_language()
deactivate()
url = reverse(things)
activate(current_lang)

适用于使用activate(target_lang)获取其他语言版本,但如果我deactivate我只是获取默认语言的网址(/en/account/,但我想要/account/)。< / p>

我已经认为让备用语言版本过于复杂,但我根本无法管理。任何提示? (无需手动从网址中剥离LANGUAGE_CODE

更新:我也尝试了

from django.core.urlresolvers import get_resolver
get_resolver(None).reverse(*args, **kwargs)

但获得NoReverseMatch

2 个答案:

答案 0 :(得分:2)

我认为最简单的方法是让Django使用语言前缀解析URL,然后只删除语言前缀。

您可以编写以下功能:

import re
from django.core.urlresolvers import reverse

def reverse_no_i18n(viewname, *args, **kwargs):
    result = reverse(viewname, *args, **kwargs)
    m = re.match(r'(/[^/]*)(/.*$)', result)
    return m.groups()[1]

现在,您可以在代码中的任何位置执行以下操作:

from myproject.utils import reverse_no_i18n

def my_view(request):
    return HttpResponseRedirect(reverse_no_i18n('my_view_name'))

您可能还想创建一个调用自定义函数的自定义{% url %}模板标签。

答案 1 :(得分:0)

我也花了一些时间找到一个好的解决方案,这是我的。

在主网址文件('my_project / urls.py')旁边,创建具有以下内容的文件'my_project / urls_without_lang.py'。

然后,您可以使用reverse('viewname', urlconf='my_project.urls_without_lang')

from copy import copy

from django.urls.resolvers import LocaleRegexURLResolver

from .urls import urlpatterns as urlpatterns_i18n

"""
Purpose of this file is to be able to reverse URL patterns without language prefix.
This is usefull to build URL meant to be communicated "outside" of the domain without any language duty.

To use it with 'reverse' method (from django.shortcuts module), simply give the additional parameter:
    `urlconf='my_project.urls_without_lang'`
Example: `reverse('viewname', urlconf='my_project.urls_without_lang')`
"""

urlpatterns = copy(urlpatterns_i18n)
for el in urlpatterns_i18n:
    if isinstance(el, LocaleRegexURLResolver):
        urlpatterns.remove(el)
        urlpatterns += el.url_patterns

希望对您有所帮助。

相关问题