使用post方法提交表单时出错

时间:2018-04-26 07:30:44

标签: python django api django-csrf

错误:CSRF令牌丢失或不正确。想要传递令牌以提交不在django模板上的表单。

  

views.py

....
def post(self, request):
    form = self.form_class(request.POST or None, request.FILES or None)
    if form.is_valid():
        email = form.cleaned_data.get('email')
        user = authenticate(email=email)
        if user is None:
            form.save()
            message = 'Saved Successfully'
            return HttpResponse(message)
        else:
            message = 'User Exists'
            return HttpResponse(message)
    else:
        message = 'Invalid form data'
        return HttpResponse(message)
....
  

form.html

....
<h1>Register</h1>
<form class="newform" action="/api/register/" method='POST'enctype="multipart/form-data">
    <input type='hidden' name='csrfmiddlewaretoken' value="some token value" />
    ....
</form>
....

2 个答案:

答案 0 :(得分:2)

CSRF(跨站点请求伪造)保护的重点是阻止提交不由同一站点提供的表单。如果您确实需要使用来自不同站点的表单来提供html页面,则必须禁用CSRF保护。如果您只需手动创建表单并通过Django视图从同一站点提供表单,则可以使用JavaScript填充csrfmiddlewaretoken字段。首先,如Django文档中所述从cookie中提取令牌:https://docs.djangoproject.com/en/2.0/ref/csrf/#ajax然后您可以填充该字段。

JQuery示例:

$(function() {
// using jQuery
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = $.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');
$('input[name=csrfmiddlewaretoken]').attr('value', crsftoken);
});

答案 1 :(得分:0)

在表单中使用{%csrf_token%}:

<form>
{% csrf_token %}
<input ... >
</form>