2

在语言切换器表单中选择语言后,出现 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 时,该表单运行良好。

4

1 回答 1

2

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

  return render(req, 'art.html', {'highlight': highlight, 'exhibitions': exhibitions})
于 2017-01-31T15:11:10.510 回答