Getting 403 (Forbidden) when trying to send POST to set_language view in Django
<p>I'm new to Django and am trying to create a small website where I click on a flag and the language changes. I'm using django i18n for that:</p>

<p><strong>urls.py</strong></p>

<pre><code>from django.conf.urls import patterns, include, url
from django.conf.urls.i18n import i18n_patterns

urlpatterns = [url(r'^i18n/', include('django.conf.urls.i18n'))]

urlpatterns += i18n_patterns(
    url(r'^$', views.home, name='home'),
)
</code></pre>

<p>The problem is, when I run the following code:</p>

<p><strong>templetatags.py</strong></p>

<pre><code>@register.simple_tag
def test():
    r = requests.post('http://localhost:8000/i18n/setlang/', data = {'lang':'en', 'next' : '/'})
    print r.status_code
</code></pre>

<p><strong>home.html</strong></p>

<pre><code>&lt;div id='country_flags'&gt;
    &lt;a hreflang="en" href="{% test %}"&gt;&lt;img id='en' src='{% static "mysyte/images/gb.png" %}'&gt;&lt;/a&gt;
&lt;/div&gt;
</code></pre>

<p>the result of r.status_code is 403.</p>

<p>What am I doing wrong?</p>

<p>Any POST request in django requires you to send the CSRF-Cookie by default. Your options around this:</p>

<ul>
<li>Don't use a POST request. Use GET instead.</li>
<li>Send the CSRF-Token with the request. <a href="https://docs.djangoproject.com/en/1.9/ref/csrf/" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/csrf/</a></li>
<li>use the decorator <code>@csrf_exempt</code> to remove any csrf-protection from a view (in your case the view for <code>http://localhost:8000/i18n/setlang/</code>)</li>
<li>don't send a request to your own app. use a link for the user to click on. probably your best option.</li>
</ul>

<blockquote>
  <p>Note:
  if you want to use the decorator w/ a class-based view, decorate the dispatch() function of that view</p>
</blockquote>

python django internationalization django-i18n