Система Django Favorite
Я пытаюсь построить систему "добавить в избранное" в django для своего приложения.
На данный момент у меня есть страница с подробным описанием объявления под названием ad_detail, где есть кнопка, при нажатии на которую пользователь, независимо от того, нажимал он уже на нее или нет, добавляет или удаляет объявление в свой "список наблюдения". Это работает нормально.
Теперь я пытаюсь сделать то же самое, но в home.html, где у меня есть пара объявлений, которые я вывожу в шаблон
- For each ad, I want to add the "add to watch list" button.
- If the user has aleady added the ad in his favorites, then show the bookmark-check-fill. If not show simply the bookmark-check.
- When the user clicks on one of the displayed "add to favorite" button, then I want in views.py to be able to get the exact button that has been clicked, to then add the related ad to user's favorites.
Код ниже:
models.py
class VlandAd(models.Model):
metaverse_name = models.CharField(max_length=100)
title = models.CharField(max_length=100)
description = models.TextField(null=True, blank=True)
price = models.CharField(max_length=50)
currency = models.CharField(max_length=8)
ad_link = models.CharField(max_length=200)
sold = models.BooleanField(default=False)
bought_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="has_bought")
created = models.DateTimeField(auto_now_add=True)
published = models.CharField(max_length = 30, choices=STATUS_CHOICES, default="Published" )
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
watch_list = models.ManyToManyField(User, related_name="has_watch_list", default=None, blank=True)
screen_pic = models.ImageField(blank=True, null=True, upload_to='images/')
home.html
{% for ad in active %}
<!--- code for card layout -->
{% if user.is_authenticated %}
<div id="add_to_watch_list_{{ad.id}}">
<form method="POST" action="{% url 'home' %}">
{% csrf_token %}
<input type="hidden" name="{{ad.id}}" value="{{ad.id}}">
<button type="submit" class="btn" data-bs-toggle="tooltip" data-bs-placement="right" title="{{tooltip_title}}">
<i class="bi-{{watch_list_icon}}" style="font-size: 2rem; color: #de4b2b;"></i>
</button>
</form>
</div>
{% endif %}
{% endfor %}
views.py
def HomePageView(request):
active = VlandAd.objects.filter(sold=False, published="Published")[:20]
sold = VlandAd.objects.filter(sold=True)
tooltip_title = ""
watch_list_icon = ""
print(active)
# ADD TO WATCH LIST LOGIC
for element in active:
if element.watch_list.filter(id=request.user.id).exists():
tooltip_title = "Remove from Watch List"
watch_list_icon = "bookmark-check-fill"
else:
tooltip_title = "Add to Watch List"
watch_list_icon = "bookmark-check"
context = {
'active': active,
'sold': sold,
'tooltip_title': tooltip_title,
'watch_list_icon': watch_list_icon
}
return render(request, "vland_store/home.html", context)
Проблемы :
If in ad_detail, when logged in I click on "add to watch list" button, then I don't see the ad in my watch-list in home.html. Meaning, that I end up with icon-not-fill instead of icon-fill and "Add to Watch List" as tooltip text instead of "Remove from Watch List".
I have troubles to get the button actually clicked in the loop in views.py.
В файле views.py, я думаю, я мог бы сделать что-то вроде этого :
if request.method == 'POST':
name = request.POST.get('name')
ad_to_add = VlandAd.objects.filter(id=name)
if ad_to_add.watch_list.filter(id=request.user.id).exists():
ad_to_add.watch_list.remove(request.user)
tooltip_title = "Add to Watch List"
watch_list_icon = "bookmark-check"
print("Add removed from watch list")
else:
ad_to_add.watch_list.add(request.user)
tooltip_title = "Remove to Watch List"
watch_list_icon = "bookmark-check-fill"
print("success add to watch list")
Но в shell, если я печатаю имя, возвращается None...
Любая помощь приветствуется.
NOTE : Если у вас есть лучший подход к этому, я готов взглянуть на него.
Спасибо большое!