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