禁止(403)CSRF验证失败。请求在Django 1.11上中止

时间:2018-03-18 11:13:19

标签: python django

我正在用Django 1.11撰写评论页面。我已经在模板中添加了{% csrf_token %},但仍然收到错误消息

  

禁止(403)CSRF验证失败。请求中止。

我的代码如下:

from django.shortcuts import render_to_response
from restapp.models import Restaurant
from restapp.models import Food
from django.http import HttpResponseRedirect
from restapp.models import Restaurant
from django.utils import timezone
from django.template import RequestContext

def comment(request,id):
    if id:
        r = Restaurant.objects.get(id=id)
    else:
        return HttpResponseRedirect("/restaurants_list/")
    if request.POST:
        visitor = request.POST['visitor']
        content = request.POST['content']
        email = request.POST['email']
        date_time = timezone.localtime(timezone())
        Comment.objects.create(
            visitor=visitor,
            email=email,
            content=content,
            date_time=date_time,
            restaurant=r
        )
    return render_to_response('comments.html', context=locals())

这是我的模板:

<!doctype html>
<html>
    <head>
        <title>Comments</title>
        <meta charset='utf-8'>
    </head>
    <body>
        <h2>{{r.name}}的評價</h2>
        {% if r.comment.all %}
            <p>目前共有{{r.comment.all|length}}的評價</p>
            <table>
                <tr>
                    <th>留言者</th>
                    <th>時間</th>
                    <th>評價</th>
                </tr>
            {% for c in r.comment.all %}
                <tr>
                    <td>{{c.visiter}}</td>
                    <td>{{c.date_time | date:"F j, Y"}}</td>
                    <td>{{c.content}}</td>
                </tr>
            {% endfor %}
            </table>
        {% else %}
            <p>無評價</p>
        {% endif %}

        <br/ ><br/ >

        <form action="" method="post">{% csrf_token %}
            <table>
                <tr>
                    <td><label for="visitor">留言者:</label></td>
                    <td><input id="visitor" type="text" name="visitor"></td>
                </tr>
                <tr>
                    <td><label for="email">電子信箱:</label></td>
                    <td><input id="email" type="text" name="email"></td>
                </tr>
                <tr>
                    <td><label for="content">評價:</label></td>
                    <td><textarea id="content" rows="10" cols="48" name="content"></textarea></td>
                </tr>
            </table>
            <input type="submit" value="給予評價">
        </form>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

如果您对csrf验证不感兴趣,请使用csrf_exempt。

请参阅此处的文档。

https://docs.djangoproject.com/en/dev/ref/csrf/#django.views.decorators.csrf.csrf_exempt