Skip to main content
 首页 » 编程设计

python之Django:禁止(CSRF token 丢失或不正确。)

2024年08月19日31insus

我的 django 版本是 1.11.4,我正在我的书中做一个简单的练习,我需要制作一个网页,人们可以提交他们对选定餐厅的评论。

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

View .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)) 

评论.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 %},在 View 函数中使用了 RequestContext(request) 并尝试了我从 Internet 搜索的几种方法。但它仍然不起作用。

有人可以帮我吗?谢谢!

请您参考如下方法:

你应该使用一本更新的书。 render_to_response 已弃用,不应在此处使用 RequestContext。此外,传递 locals 是一种可怕的反模式,尽管这不是导致问题的原因。

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