손예준
손예준

Reputation: 31

Add value on IntegerField with a button(Django 1.11)

models.py

likes = models.IntegerField()

forms.py

class LikeForm(forms.ModelForm):
class Meta:
    model = Post
    fields = ("likes",)

How could I make a button that add 1 to this IntegerField every time it's clicked? The default value is 0.

I'm guessing I have to use "submit" button but I'm not sure how I can do that with out rendering the form on the page.

Upvotes: 1

Views: 571

Answers (1)

Daniel Holmes
Daniel Holmes

Reputation: 2002

In your views.py you could add something like this:

def record_like_view(request, pk):
    if request.method == 'POST':
        post = Post.objects.get(pk=pk)
        post.likes += 1
        post.save()
    ...

Then in your template:

<form method="post">
    {% csrf_token %}
    <a class="btn" href="{% url 'my_app:record_like' post.id %}">Like</a>
</form>

You are just posting to a URL. Even though you are still using a form in your template, there is no need for the LikeForm in this case. Take a look at this Django tutorial for another example.

As far as a user preventing a user from clicking multiple times (as pointed out by guillermo) this would require something a little more complicated.

Upvotes: 1

Related Questions