django中缺少csrf令牌

时间:2016-02-17 02:27:53

标签: django csrf

我有关于django csrf的问题。这是我的观看代码。

    if request.user.is_authenticated():
      res = {"is_authenticated": "true"}
    else:
      res = {}

    return render_to_response('app/index.html', res, context_instance=RequestContext(request))

2 个答案:

答案 0 :(得分:0)

检查CsrfViewMiddleware中的MIDDLEWARE_CLASSES元组中是否添加了settings.py,然后您只需在模板中执行{% csrf_token %}即可获取令牌。

<强> settings.py

MIDDLEWARE_CLASSES = (
    ...
    ...
    'django.middleware.csrf.CsrfViewMiddleware',
    ...
    ...
)

应用/ index.html中

<form action="" method="post">{% csrf_token %}

有关详细信息,请参阅documentation

答案 1 :(得分:-2)

在你的views.py中使用函数上方的@csrf_exempt装饰器,为此需要首先导入这个装饰器

@csrf_exempt
def sample_func(request):
    if request.user.is_authenticated():
        res = {"is_authenticated": "true"}
    else:
        res = {}
    return render_to_response('app/index.html', res, context_instance=RequestContext(request))

然后在你的视图函数中使用它,例如

<form method="" action="">
{% csrf_token %}

.......

</form>

然后在你的index.html文件中调用这个装饰器的表单标签就像这样

$showTeamInfoTitles = array("Team Id","Team Name","Captain");

$showTeamInfo = " SELECT teamid, teamname, captain FROM teams WHERE teamid= ?";

$whichteam=5;


function displayresults($query,$columntitles,$whichteam) {

    $dbh = database_connect();
    $sth = $dbh->prepare($query);
    $sth->bindValue(1, $whichteam, PDO::PARAM_STR);

    $sth->execute();
    $result = $sth->fetchAll();


    echo "<table border='1'>";
    echo "<tr>";

    while (list($key, $value) = each($columntitles)) {
        echo "<th>" . $value . "</th>";
    } 

    echo "</tr>";