Search code examples
pythondjangomany-to-manycs50

ManyToManyField Data not showing up


Good day,

i have got a problem with adding a listing to the watchlist of a specific user. Any tips on how i could fix this? I have tried to create a seperate model and that inherits from the listing model.

The model structure

class Listing(models.Model):
    user = models.ForeignKey(User, on_delete=models.PROTECT, default='',  null=True )
    title = models.CharField(max_length=200)
    description = models.TextField()
    image = models.ImageField(upload_to='media/')
    price = models.FloatField()
    category = models.ForeignKey(Category,on_delete=models.CASCADE,default='')
    # a listing can have multiple watchers and a watcher can have multiple listings
    watchers = models.ManyToManyField(User,blank=True,null=True,related_name="listings")
    
    def __str__(self):
        return "%s" % (self.title)

Code of the view

def listing(request, id):
    comment_form = AddComment()
    bid_form = AddBid()
    listing =  Listing.objects.get(id=id)
    if request.method == "POST":
        if "watchlistBtn" in request.POST:
            listing.watchers.add(request.user)
            listing.save()
    return render(request, "auctions/listing.html", {
        "listing": listing,
        "comment_form": comment_form,
        "bid_form": bid_form
    })


# watchlist

@login_required(login_url='/login')
def watchlist(request):
    listings = request.user.listings.all()
    
    return render(request,"auctions/watchlist.html", {
        "listings": listings
    })

The code of the form template

 <form action="{% url 'watchlist' %}" method="post">
            {% csrf_token %}
            <input type="submit" value="Add to Watchlist" class="btn btn-primary" name="watchlistBtn">
        </form>

Solution

  • I'd double check that the User is actually in the field, using the shell:

    Listing.objects.all().first().watchers.all()
    # ^ or something similar
    

    And if they are, you could always grab Listings by the other way:

    listings = Listing.objects.filter(watchers__in=[request.user])
    

    essentially the same thing