Question

I have a form that currently redirects to the index page :

    {% 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 %}

How can I make it redirect to the same page ?

Was it helpful?

Solution

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 }}"/>

OTHER TIPS

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

I'm not entirely sure I understood the problem, but I believe you can use something like this.

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

And than extend the page based on language

This is simpler

from django.utils.translation import get_language

def strip_lang(value):
    lang = get_language()
    return '/%s' % value.lstrip('/%s/' % lang)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top