Adding watchlist. Watchlist not displaying added items

I am trying to work on a project and one of the features is that users who are signed in should be able to visit a Watchlist page, which should display all of the listings that a user has added to their watchlist.

So far, I am redirected when ‘add to watchlist’ is clicked but it does not bring up the button of ‘remove from watchlist’ and also when it redirects me to the watchlist page (where i should view the users entire watchlist), it shows me ‘No watchlist found.’.

I have triple-checked and I am iterating properly (I think) but I don’t know why it is not showing any of the watchlist)

URLS.PY

    path("add_watchlist/<int:listing_id>/", views.add_watchlist, name="add_watchlist"),
    path("watchlist", views.watchlist, name="watchlist"),

MODELS.PY

class Watchlist(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    item = models.ManyToManyField(Auction)

    def __str__(self):
        return f"{self.user}'s watchlist"

LAYOUT.HTML

                    <li class="nav-item">
                            <a class="nav-link" href="{% url 'all_category' %}?category={{ category.name}}">Category</a>
                    <li class="nav-item">
                        <a class="nav-link" href="{% url 'create_listing' %}">Sell</a>
                    </li>
                    <li class="nav-item">
                        {% if user.is_authenticated %}
                        <a class="nav-link" href="{% url 'watchlist' %}">Watchlist</a>
                        {% endif %}
                    </li>
                </ul>

VIEWS.PY

@login_required
def add_watchlist(request, listing_id):
    items = Auction.objects.get(pk=listing_id)
    watched = Watchlist.objects.filter(user=request.user, item=listing_id)

    if request.method == 'POST':
        if watched.exists():
            watched.delete()
            messages.success(request, 'Listing removed from watchlist')
            # messages.add_message(request, messages.ERROR, "Successfully deleted from your watchlist")
            return HttpResponseRedirect(reverse("watchlist"))
            
        else:
            watched, created = Watchlist.objects.get_or_create(user=request.user)
            watched.item.add(items)
            messages.success(request, 'Listing removed from watchlist')
            # messages.add_message(request, messages.SUCCESS, "Successfully added to your watchlist")
            return redirect('index')
    else:
        return HttpResponseRedirect(reverse("watchlist")) 

@login_required
def watchlist(request):
    watchlists = Watchlist.objects.all()
    context = {'watchlists':watchlists}
    return render(request, 'auctions/watchlist.html', context)  

DETAILS.HTML

                            {% if request.user.is_authenticated %}
                            <div class="my-2">
                                <form method="POST" action="{% url 'add_watchlist' detail.id %}" class="form-inline">
                                    {% csrf_token%}
                                    
                                    {% if watched %}
                                        <input class="btn btn-secondary btn-block" type="submit" value="Remove from Watchlist" />
                                    {% else %}
                                        <input class="btn btn-secondary btn-block" type="submit" value="Add to Watchlist" />
                                    {% endif %}
                                </form>
                            </div>
                        {% endif %}
                        </div>

WATCHLIST.HTML

            <div class="container pb-4">
                <div class="row text-center">
                    {% for watchlist in watchlists %}
                        <div class="col-lg-3 col-sm-4">
                            <a href={% url 'listing_detail' watchlist.id %} class="btn btn-outline-dark btn-sm m-1">
                                    {% if watchlist.image_url %}
                                        <img src='{{ watchlist.image_url }}' alt="{{ watchlist.title }}" style="width:100%">
                                    {% else %}
                                        <img src="https://demofree.sirv.com/nope-not-here.jpg">
                                    {% endif %}  
                                        <h5 class="card-title mb-0">{{ watchlist.title }}</h5>
                            </a>
                        </div>
                    {% empty %}
                        <p>No watchlist found.</p>
                    {% endfor %}
                </div>
            </div>  

#EDIT
I also tried to use a related name to the model to get the watchlist but it didnt work. Please see alteration below;

MODELS.PY

class Watchlist(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    item = models.ManyToManyField(Auction, related_name='watchlistings',)

    def __str__(self):
        return f"{self.user}'s watchlist"

WATCHLIST.HTML

                    {% for watchlist in items.watchlistings.all %}
                        <div class="col-lg-3 col-sm-4">
                            <a href={% url 'listing_detail' watchlist.id %} class="btn btn-outline-dark btn-sm m-1">
                                    {% if watchlist.image_url %}
                                        <img src='{{ watchlist.image_url }}' alt="{{ watchlist.title }}" style="width:100%">
                                    {% else %}
                                        <img src="https://demofree.sirv.com/nope-not-here.jpg">
                                    {% endif %}  
                                        <h5 class="card-title mb-0">{{ watchlist.title }}</h5>
                            </a>
                        </div>
                    {% empty %}
                        <p>No watchlist found.</p>
                    {% endfor %}

I would install the Django Debug Toolbar and use that to inspect the situation. If that’s not your jam, I would confirm the following:

  1. Data exists (check the admin).
  2. The view you think is being used is actually being used.
  3. The template you think is being used is actually being used.

If all of the above are true, then perhaps something else is overriding the watchlists template variable later on in the view processing flow? Maybe a middleware or context processor?

2 Likes

Hi,
Have a look in your settings if there is this line
'django.middleware.cache.UpdateCacheMiddleware',
I just fix a similar error with the clue above, thanks @CodenameTim

For the time i imagine you already solved this but seems in (user=request.user, item=listing_id) must be item = items, not item=listing_id

Thank you for responding