1

我有一个当前重定向到索引页面的表单:

    {% for lang in LANGUAGES %}
        <form name="setLang{{ lang.1 }}" action="/i18n/setlang/" method="post">
            {% csrf_token %}
            <input name="next" type="hidden" value="/"/>
            <input type="image" name="language" src="/static/img/{{ lang.0 }}.png" alt="{{ lang.1 }}" value="{{ lang.0 }}"/>
            <a href="/" onclick="document.setLang{{ lang.1 }}.submit();return false;"></a>
        </form>
    {% endfor %}

我怎样才能让它重定向到同一页面?

4

4 回答 4

5

What you need is a way to get the current path, but plain - without the leading language code. Given that Django will redirect user to the correct URL automatically.

I wrote a simple function that strips current language from a given path. It's based on how django.core.urlresolvers.resolve deals with language codes in paths, so should be pretty solid:

from django.utils.translation import get_language
import re

def strip_lang(path):
    pattern = '^(/%s)/' % get_language()
    match = re.search(pattern, path)
    if match is None:
        return path
    return path[match.end(1):]

You can use it in your view to pass a language-less path to your template:

def your_view(request):
    next = strip_lang(request.path)
    return render(request,  "form.html", {'next': next})

and then use it in the template:

<input name="next" type="hidden" value="{{ next }}"/>

Alternatively you can easily make the function into a template filter and use it in your template directly:

<input name="next" type="hidden" value="{{ request.path|strip_lang }}"/>
于 2013-10-03T17:47:57.453 回答
2
<input name="next" type="hidden" value="{{ request.path }}"/>
于 2013-10-02T14:18:18.967 回答
0

我不完全确定我理解这个问题,但我相信你可以使用这样的东西。

urlpatterns = patterns('',
(r'^blablabla/(?P<language>\w{2})/categories/$', views.my_view),

而不是基于扩展页面language

于 2013-10-04T02:02:22.540 回答
-2

这个比较简单

from django.utils.translation import get_language

def strip_lang(value):
    lang = get_language()
    return '/%s' % value.lstrip('/%s/' % lang)
于 2014-08-28T14:45:19.420 回答