Reputation: 691
I have made a webapp where I can post images and other users can give a like. But if he already liked the post then it would be Red and by clicking it again it will then unlike the post and if the user didn't liked the post then it will be green and cliking the button will result liking the post. I am able to like and unlike function but I can't change the button color according to the logic. In django we cannot pass a dictionary in redirect('urlname')
.So is there any possible way to make my button green or red according to that logic given?
Codes
It is the HTML file
{% extends 'navbar-footer.html'%}
{% block content %}
<style>
.btn-like{
color: green;
}
.btn-dislike{
color: red;
}
</style>
<h1>{{button}}</h1>
<h4>This is item number {{item.id}}</h4>
<h4>{{ item.title }}</h4>
<h4>{{ item.body }}</h4>
<button type="button" class="btn {{button}}" onclick="javascript:{document.getElementById('increase_like').submit()}">Like {{item.likes}}</button>
<form action="{%url 'increase_like' item.id%}" method="POST" id='increase_like' >
{% csrf_token %}
<input type="hidden" name="" id="">
</form>
<img src="{{item.image.url}}" alt="">
{% for user in voter.voter.all %}
<h1>{{user.username}}</h1>
{% endfor %}
{% endblock %}
Views.py
def likes(request, item_id):
voter_id = Vote.objects.filter(item_product_id=item_id, voter=request.user)
if voter_id.exists():
voter_obj = get_object_or_404(Vote, item_product_id=item_id)
voter_obj.voter.remove(request.user)
item = get_object_or_404(Item_Product, pk=item_id)
item.likes = voter_obj.voter.count()
item.save()
voter_obj.save()
return redirect('/products/item_Products/'+str(item_id))
elif voter_id.exists() == False:
voter_obj = get_object_or_404(Vote, item_product_id=item_id)
voter_obj.voter.add(request.user)
item = get_object_or_404(Item_Product, pk=item_id)
vote_count = item.likes
item.likes = voter_obj.voter.count()
item.save()
voter_obj.save()
return redirect('/products/item_Products/'+str(item_id))
Upvotes: 2
Views: 101
Reputation:
Do something like this
if voter_id.exists():
# Delete the voter object or remove vote
messages.info("disliked")
else:
# Create voter object or add vote
messages.info("liked")
return redirect("YOUR_REDIRECT_URL")
Upvotes: 1
Reputation: 303
When you click run
function likeAndDislike(this) {
if (this.className.includes("btn-like")){
this.classList.add("btn-dislike");
this.classList.remove("btn-like");
}
if (this.className.includes("btn-dislike")) {
this.classList.add("btn-like");
this.classList.remove("btn-dislike");
}
}
Upvotes: 1