The bookmark functionality does work. It displays the bookmarked posts in bookmark-list.html. The only problem is that the button is not changing from ‘add’ to ‘remove’.
This is the bookmark form in food.html
{% csrf_token %} {% if is_bookmarked %}Remove
{% else %}Add
{% endif %}These are view logics:
def food(request):
country_list = Country.objects.all()
context = {'country_list ': country_list }
return render(request, 'base/food.html', context)
@login_required
def bookmarkFood(request, post_id):
user = request.user
country = get_object_or_404(Country, id=post_id)
bookmark, created = FoodBookmark.objects.get_or_create(user=user)
is_bookmarked = bookmark.post.filter(id=post_id).exists()
if request.method == "POST":
if user.is_authenticated:
if is_bookmarked:
bookmark.post.remove(jobinfo)
print('removed')
print(f"is_bookmarked: {is_bookmarked}")
else:
bookmark.post.add(jobinfo)
print('added')
print(f"is_bookmarked: {is_bookmarked}")
is_bookmarked = bookmark.post.filter(id=post_id).exists()
return redirect('food')
models.py
class Country(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name=‘country’)
created = models.DateTimeField(auto_now_add=True)
form_submitted = models.BooleanField(default=False)
class Food(models.Model):
country = models.ForeignKey(Country, on_delete=models.CASCADE)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
class FoodBookmark(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ManyToManyField(Country, related_name=“bookmarkfood”)
urls.py
path(‘food/’, views.food, name=“food”),
path(‘bookmark-food/int:post_id/’, views.bookmarkFood, name=“bookmarkFood”),