Django1.10 - / i18n / setlang / CSRF令牌丢失或不正确

时间:2017-01-31 13:49:52

标签: internationalization csrf django-1.10

在语言切换器表单中选择语言后,我收到了CSRF错误:

表单位于 base.html

<form action="{% url 'set_language' %}" method="post" class="form-inline">
  {% csrf_token %}
  <input name="next" type="hidden" value="" />
  <div class="form-group">
    <div class="input-group">
      <div class="input-group-addon"><i class="fa fa-globe" aria-hidden="true"></i></div>
      <select name="language" class="form-control" id="lang-switcher">
        {% 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>
    </div>
  </div>
</form>

我用JS提交表格:

jQuery('#lang-switcher').change(
    function(){
        jQuery(this).closest('form').trigger('submit');
    });

我的模板文件 art.html 如下:

{% extends "base.html" %}
{% load staticfiles %}
{% load i18n %}

{% block content %}
  ....
{% endblock %}

views.py 如下:

from django.template import RequestContext
from django.shortcuts import render_to_response

from .models import Exhibition, Picture

def index(req):
  highlight = Exhibition.objects.latest()
  exhibitions = Exhibition.objects.all()[1:]
  return render_to_response('art.html', RequestContext(req,{'highlight': highlight, 'exhibitions': exhibitions}))

urls.py 如下:

urlpatterns = [
  url(r'^i18n/', include('django.conf.urls.i18n')),
  url(r'^admin/', admin.site.urls),
  url(r'^art/', index),
  url(r'^$', views.flatpage, {'url': '/home/'}, name='home')
]

我可以加载没有问题的页面,然后当我提交表单切换语言时,我收到了CSRF错误。

修改

我必须补充说,当我在root上时,表单效果很好。

1 个答案:

答案 0 :(得分:1)

我终于通过在我的视图中使用不同的渲染功能来解决它​​:

  return render(req, 'art.html', {'highlight': highlight, 'exhibitions': exhibitions})