1

I am trying to create a page that includes multiple forms, and I want to build something like a "like button" so that I can "like" some posts in a page. I also want to put some restriction so that I can like every post, but can only like each post once

Now I encounter a problem that I can only "like" a post. When I click another "like" to another post, csrf error would occur(CSRF verification failed. Request aborted.). I want to know how to like multiple posts in a page at the same time.

Does it have something to do with how and where to put {% csrf_token %}? This article(How Will the Inclusion of Two Forms Affect my CSRF Token Use?) says I should put {% csrf_token %} in every form, but it doesn't seem to work.

Here's my code:

models.py

class Restaurant(models.Model):
    name = models.CharField(max_length=20)
    phone_number = models.CharField(max_length=15)
    address = models.CharField(max_length=50, blank=True)
    likes = models.DecimalField(max_digits=2,decimal_places=0, default=0)

views.py

<!doctype html>
<html>
<head>
    <title> Menu </title>
    <meta charset='utf-8'>
</head>
<body>
    <h2>餐廳列表</h2>

    <table>
        <tr>
            <th>ID</th>
            <th>NAME</th>
            <th>PHONE</th>
            <th>ADDRESS</th>
            <th>LIKES</th>
            <th>LIKE IT!</th>
        </tr>
        {% for r in restaurants %}
            <tr>
                <td> {{ r.id }} </td>
                <td> {{ r.name }} </td>
                <td> {{ r.phone_number }} </td>
                <td> {{ r.address }} </td>
                <td> {{ r.likes }} </td>
                <td>
                <form id={{ r.id }} action="" method="post">
                    {% csrf_token %}
                    <input type="hidden" name="ok" value="yes">
                    <input class="submit" type="submit" value="Upvote">
                </form>
                </td>

            </tr>
        {% endfor %}
    </table>

    </form>
</body>
</html>

views.py

def list_restaurants(request):
    restaurants = Restaurant.objects.all()

    if request.method == "POST":
        post = Restaurant.objects.get(id=request.POST['id'])
        post.likes += 1
        post.save()
        return render_to_response('restaurants_list.html',locals())
    else:
        return render(request, 'restaurants_list.html',locals())
Community
  • 1
  • 1
CYH16
  • 33
  • 9

1 Answers1

0

change

return render_to_response('restaurants_list.html',locals())

to

return render(request, 'restaurants_list.html',locals())
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49
  • Thanks for the suggestion, but what if I want to put some restriction so that I can like every post, but can only like each post once? – CYH16 Apr 09 '17 at 13:43
  • Its another logic. You have to save which user like which post. You have to build that – itzMEonTV Apr 09 '17 at 13:46