繁体   English   中英

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

[英]Django: Forbidden (CSRF token missing or incorrect.)

我的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) ,并尝试了几种从Internet搜索的方法。 但这仍然行不通。

有人可以帮我吗? 谢谢!

您应该使用更新的书。 render_to_response已被弃用,这里不应使用RequestContext 此外,通过locals是一种可怕的反模式,尽管这不是造成问题的原因。

return render(request, 'comments.html', {'r': r})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM