Django - 403 Forbidden - CSRF令牌丢失或不正确

时间:2013-11-19 19:51:16

标签: python django python-2.7 django-views

当我按下“退出”按钮时,我已更新到Django 1.6并遇到CSRF令牌问题。

我的代码:
--views.py

@login_required(login_url='/login/')
def show_matches(request):
    errors = []
    logged = True
    if request.method == "POST":
        if 'edit' in request.POST:
            return HttpResponseRedirect("/edit_matches/")
        elif 'view' in request.POST:
            return HttpResponseRedirect("/view_matches/")
        elif 'logout' in request.POST:
            return HttpResponseRedirect("/logout/")
        else:
            errors.append('Incorrect operation!')
    return render_to_response('admin/match_main.html', RequestContext(request, locals()))  

- match_show.html

{% extends "admin/base_admin.html" %}
{% block title %}Administration referee page {% endblock %}
{% block content %}
        <form action='.' method='post'>{% csrf_token %}
            <input class="btn btn-medium btn-primary" type="submit" value="Edit Matches" name="edit" />
            <input class="btn btn-medium btn-primary" type="submit" value="View Matches" name="view" />
        </form>
{% endblock %}

如何解决这个问题?

2 个答案:

答案 0 :(得分:4)

添加隐藏输入

<input type='hidden' name='csrfmiddlewaretoken' value='{{csrf_token}}'>

答案 1 :(得分:3)

您显示的模板不包含注销按钮。如果要使用发布请求注销,则必须在包含注销按钮的表单中包含csrf标记。