<h2>修复</h2>
<p><strong>1</strong>。在模板中的表单标记中包含<code>{% csrf_token %}</code><strong>。</p>
<p><strong>2</strong>。如果出于任何原因在Django 1.3及更高版本上使用<code>render_to_response</code>,请将其替换为<a href="https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#render" rel="nofollow noreferrer">the ^{<cd3>} function</a>。替换为:</p>
<pre><code># Don't use this on Django 1.3 and above
return render_to_response('contact.html', {'form': form})
</code></pre>
<p>有了这个:</p>
<pre><code>return render(request, 'contact.html', {form: form})
</code></pre>
<p><a href="http://django.readthedocs.io/en/1.3.X/releases/1.3.html#everything-else" rel="nofollow noreferrer">The ^{<cd3>} function was introduced in Django version 1.3</a>-如果您使用的是古版本<a href="http://django.readthedocs.io/en/1.2.X/topics/http/shortcuts.html#render-to-response" rel="nofollow noreferrer">like 1.2 or below</a>,则必须将<code>render_to_response</code>与a<code>RequestContext</code>一起使用:</p>
<pre><code># Deprecated since version 2.0
return render_to_response('contact.html', {'form': form},
context_instance=RequestContext(request))
</code></pre>
<h2>什么是CSRF保护?我为什么要它?</h2>
<p>这是一种攻击,敌人可以强迫你的用户做一些不愉快的事情,如转移资金,更改他们的电子邮件地址,等等:</p>
<blockquote>
<p>Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. With a little help of social engineering (such as sending a link via email or chat), an attacker may trick the users of a web application into executing actions of the attacker's choosing. If the victim is a normal user, a successful CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address, and so forth. If the victim is an administrative account, CSRF can compromise the entire web application. Source: <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)" rel="nofollow noreferrer">The Open Web Application Security Project</a></p>
</blockquote>
<p>即使您现在不关心这种事情,应用程序可能会增长,因此最佳做法是保持CSRF保护。</p>
<h2>CSRF保护不应该是可选的吗?</h2>
<p>它是可选的,但在默认情况下打开(默认情况下包括CSRF中间件)。您可以关闭它:</p>
<ul>
<li>通过使用<code>csrf_excempt</code>装饰器对特定视图进行装饰。</li>
<li>对于每个视图,从<code>settings.py</code>的中间件列表中删除CSRF中间件</li>
</ul>
<p>如果在系统范围内关闭它,则可以通过使用<code>csrf_protect</code>装饰器对特定视图进行装饰来打开它。</p>