Watchlist system on django

烈酒焚心 提交于 2021-02-19 08:22:06

问题


I want to know how to create a whatchlist on django, it could be like a function to select favourite objects as well.

This is the code I've so far

models.py

class Watchlist(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
    object = models.ForeignKey(Object, on_delete=models.CASCADE)

views.py

def watchlist(request):
    return render(request, "auctions/watchlist.html", {
        "watchlists": Watchlist.objects.all()
    })

I didn't start html yet

My idea it's to put an add button where if the user doesn't have the auction listing on his watchlist, and a remove button if it has the object on the watchlist. could anyone help me to finish it, thanks.


回答1:


models.py

class User(AbstractUser):
    pass

class Product(models.Model):
    title=models.CharField(max_length=50)
    desc=models.TextField()
    initial_amt=models.IntegerField()
    image=models.ImageField(upload_to='product')
    category=models.CharField(max_length = 20, choices =CHOICES)
    def __str__(self):
        return f"Item ID: {self.id} | Title: {self.title}"

class Watchlist(models.Model):
   user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
   item = models.ManyToManyField(Product)
   def __str__(self):
       return f"{self.user}'s WatchList"

Here the products and watchlist are linked by many to many field since a product can be present in multiple user's watchlists and a user can have multiple items in the watchlist.

views.py

adding the product in the watchlist

def watchlist_add(request, product_id):
    item_to_save = get_object_or_404(Product, pk=product_id)
    # Check if the item already exists in that user watchlist
    if Watchlist.objects.filter(user=request.user, item=item_id).exists():
        messages.add_message(request, messages.ERROR, "You already have it in your watchlist.")
        return HttpResponseRedirect(reverse("auctions:index"))
    # Get the user watchlist or create it if it doesn't exists
    user_list, created = Watchlist.objects.get_or_create(user=request.user)
    # Add the item through the ManyToManyField (Watchlist => item)
    user_list.item.add(item_to_save)
    messages.add_message(request, messages.SUCCESS, "Successfully added to your watchlist")
    return render(request, "auctions/watchlist.html")

The button can be added like this:

<a href="{% url 'watchlist_add' product.id %}" role="button" class="btn btn-outline-success btn-lg">Add to Watchlist</a>


来源:https://stackoverflow.com/questions/63403309/watchlist-system-on-django

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!