I'm creating a Truth System for my project PoopFacts, where people can vote for True, False, or remove their vote.
I have the voting system working, but I'm trying to make the button change colors to show if they've voted for True of False already or uncasted their vote.
I'm showing the "Like button" code, cause it's simpler and uses the same logic.
.models
PoopFact(models.Model):
likes = models.ManyToManyField(User, related_name='likes')
.views
def home(request):
poopfacts = PoopFact.objects.all().order_by('-date')
context = {'form': form, 'poopfacts':poopfacts,}
return render(request, 'home.html', context)
The idea is pretty much something like this
html
{% for poopfact in poopfacts %}
{% if poopfact.likes.user.exists() %}
<button type="submit" >Like</button>
{% else %}
<button type="submit" >Like</button>
{% endif %}
So if they've liked it, the button will be blue, and if they click it again it will uncast their vote and make it normal.
Does anybody have a good idea to make this work? I've been trying so many things with no luck.
CodePudding user response:
in html
{% for poopfact in poopfacts %}
{% if user in poopfact.likes.all %}
<button type="submit" >Like</button>
{% else %}
<button type="submit" >Like</button>
{% endif %}
{% endfor %}