Django change language in html

2019-09-13 03:03发布

问题:

In the Django Translation documentation, it gives this way of changing the language of the site:

{% load i18n %}

<form action="{% url 'set_language' %}" method="post">{% csrf_token %}
    <input name="next" type="hidden" value="{{ redirect_to }}" />
    <select name="language">
        {% get_current_language as LANGUAGE_CODE %}
        {% get_available_languages as LANGUAGES %}
        {% get_language_info_list for LANGUAGES as languages %}
        {% for language in languages %}
            <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}>
                {{ language.name_local }} ({{ language.code }})
            </option>
        {% endfor %}
    </select>
    <input type="submit" value="Go" />
</form>

What I want to do instead is have two buttons(two divs actually) that when pressed change the language accordingly(el for Greek and en for English). How can I change that form into what I want to do? Sorry if it's simple, I'm not that good with forms... I tried something else:

<div id="english">
                <img id="english_flag" src="{% static "en.png" %}"/>
            </div>
            <script>
            $('#english').click(function(){
                  $.ajax({
                           type: "POST",
                           url: "{% url 'set_language' %}",
                           data: {'language': 'en', 'csrfmiddlewaretoken': '{{ csrf_token }}'},
                           success: function(response) {
                                location.reload();
                            },
                            error: function(rs, e) {
                                   alert(e);
                            }
                      });
                })
            </script>
            <div id="greek">
                <img id="greek_flag" src="{% static "el.png" %}"/>
            </div>
            <script>
            $('#greek').click(function(){
                  $.ajax({
                           type: "POST",
                           url: "{% url 'set_language' %}",
                           data: {'language': 'el', 'csrfmiddlewaretoken': '{{ csrf_token }}'},
                           success: function(response) {
                                location.reload();
                            },
                            error: function(rs, e) {
                                   alert(e);
                            }
                      });
                })
            </script>

And it's working just fine. A bit more testing and I'm going to answer my question...