steerr
steerr

Reputation: 150

Handling votes through forms

I installed django-vote which has a simple API:

review = ArticleReview.objects.get(pk=1)

# Up vote to the object
review.votes.up(user_id)

# Down vote to the object
review.votes.down(user_id)

I've got a Car page with multiple reviews that I wish to vote. I tried:

<form action="{% url 'reviews:review-vote' review.id %}" method="GET">
    <button type="submit" name="vote-up"></button>
    <button type="submit" name="vote-down"></button>
</form>

URL:

url(r'^(?P<review_id>\d+)/vote/$', views.review_vote, name="review-vote"),

View:

def review_vote(request, review_id):
    if request.GET.get("vote-up"):
        review = Review.objects.get(id=review_id)
        review.votes.up(request.user.id)
    return redirect("car", {"make": review.car.make, "years": review.car.years})

This doesn't execute the vote and doesn't redirect to the Car page. I'd like to implement the voting API in my template, without reloading the page if possible.

Any suggestion or feedback will be welcomed and greatly appreciated.

Thank you.

Upvotes: 1

Views: 74

Answers (1)

badiya
badiya

Reputation: 2257

you can check if the key vote-up or vote-down which one is there in the request.GET

<form action="{% url 'reviews:review-vote' review.id %}" method="GET">
    <button type="submit" name="vote-up"></button>
    <button type="submit" name="vote-down"></button>
</form>

and in the views try this.

def review_vote(request, review_id):
    if "vote-up" in request.GET:
        review = Review.objects.get(id=review_id)
        review.votes.up(request.user.id)
    return redirect("car", {"make": review.car.make, "years": review.car.years})

Upvotes: 1

Related Questions