2
votes

My django version is 1.11.4, and I'm on a simple exercise in my book which I need to make a web page that people can submit their comments for a selected restaurant.

But it shows the message 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>

I've added {% csrf_token %} in .html, used RequestContext(request) in view function and tried several ways I searched from the Internet. But it still doesn't work.

Can somebody give me a help? Thanks!

1

1 Answers

3
votes

You should use a book that is more up to date. render_to_response is deprecated and RequestContext should not be used here. Also, passing locals is a horrible anti-pattern, although not the cause of your problem.

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