Django:Forbidden(CSRF令牌丢失或不正确。)

时间:2017-08-10 09:50:20

标签: python django

我的django版本是1.11.4,我在书中进行了一个简单的练习,我需要制作一个人们可以为所选餐厅提交评论的网页。

但它会显示消息Forbidden (CSRF token missing or incorrect.)

views.py:

def comments(request, id):
    if id != 0:
        r = Restaurant.objects.get(id = id)
    else:
        return HttpResponseRedirect('/restaurantsList/')

    if request.POST:
        dateTime = timezone.localtime(timezone.now())
        Comment.objects.create(
                content = request.POST['content'],
                visitor = request.POST['visitor'],
                email = request.POST['email'],
                dateTime = dateTime,
                restaurant = r
        )

    return render_to_response('comments.html', locals(), RequestContext(request))

comments.html:

<!doctype html>
<html>
<head>
    <title>Comments</title>
    <meta charset='utf-8'>
</head>

<body>
    <h2>Comments for {{ r.name }}</h2>

    {% if r.comment_set.all %}
        <p>We have {{ r.comment_set.all | length }} comments</p>

        <table>
            <tr>
                <th>Visitor</th>
                <th>Time</th>
                <th>Comment</th>
            </tr>

            {% for c in r.comment_set.all %}
                <tr>
                    <td>{{ c.visitor }}</td>
                    <td>{{ c.dateTime | date:'F j, Y' }}</td>
                    <td>{{ c.content }}</td>
                </tr>
            {% endfor %}
        </table>
    {% else %}
        <p>No comment</p>
    {% endif %}

    <br /><br />

    <form action='' method='post'> {% csrf_token %}
        <table>
            <tr>
                <td><label for='visitor'>Visitor: </label></td>
                <td><input id='visitor' type='text' name='visitor'></td>
            </tr>
            <tr>
                <td><label for='email'>E-mail: </label></td>
                <td><input id='email' type='text' name='email'></td>
            </tr>
            <tr>
                <td><label for='content'>Comment: </label></td>
                <td>
                    <textarea id='content' rows='10' cols='48'
                    name='content'></textarea></td>
                </td>
            </tr>
        </table>
        <input type='submit' value='Submit'>
    </form>
</body>

我已在.html中添加了{% csrf_token %},在视图功能中使用了RequestContext(request),并尝试了几种从互联网上搜索的方法。但它仍然无法发挥作用。

有人可以给我一个帮助吗?谢谢!

1 个答案:

答案 0 :(得分:3)

您应该使用更新的书籍。不推荐使用render_to_response,此处不应使用RequestContext。此外,通过locals是一种可怕的反模式,虽然不是你问题的原因。

return render(request, 'comments.html', {'r': r})
相关问题