尝试在我的 Django Web 应用程序中添加“添加到愿望清单按钮”

我正在尝试在列出书籍的页面上添加“添加到愿望清单”按钮。当用户按下该按钮时,它会将 isbn(书籍的 pk)和用户 ID 添加到愿望清单表中。由于某种原因,当我按下按钮时,它没有将它们添加到我的数据库中。没有显示任何错误,所以我不知道问题是什么。


这是我的代码


#views.py

class wishlistView(TemplateView):

    template_name = 'TextSearch/wishlist.html'


    def post(self, request, pk):

        isbn = self.request.POST.get('isbn')

        current_user = request.user

        book = wishlist(userid_id = current_user.id, ISBN_id = isbn)

        book.save()

        return

我的 HTML 代码


{% if user.is_authenticated %}

    <form method="post">

    {% csrf_token %}

    <input type="hidden" value="{{book.pk}}" name="isbn">

    <a href="{% url 'TextSearch:wishlist' book.pk %}" >Add To WishList</a>

    </form>

   {% else %}

    <a href="{% url 'User:RegisterView'  %}"  >Add To WishList</a>

   {% endif %}

我的桌子


#models.py

class wishlist (models.Model):

    userid = models.ForeignKey(User, on_delete= models.CASCADE)

    ISBN = models.ForeignKey(books, on_delete = models.CASCADE)

提前谢谢你,我是 Django 新手。


绝地无双
浏览 129回答 2
2回答

米脂

-- 问题已修复 -- 这只是一个 HTML 错误,这是更新后的代码{% if user.is_authenticated %}&nbsp; &nbsp; <form action="{% url 'TextSearch:wishlist' book.pk %}" method="post">&nbsp; &nbsp; {% csrf_token %}&nbsp; &nbsp; <input type="hidden" value="{{book.pk}}" name="isbn">&nbsp; &nbsp; <input type="submit" value="Add to wishlist">&nbsp; &nbsp; </form>&nbsp; &nbsp;{% else %}&nbsp; &nbsp; <a href="{% url 'User:RegisterView'&nbsp; %}"&nbsp; >Add To WishList</a>

潇湘沐

我个人使用这个方法我的型号:class UserWishlist(models.Model):user = models.ForeignKey(UserModel,on_delete=models.CASCADE,blank=False)products = models.ManyToManyField(Product)比我认为的:product = Product.objects.get(id=id)obj, created = UserWishlist.objects.get_or_create(user=request.user)if product in obj.products.all():&nbsp; &nbsp; obj.products.remove(product)else:&nbsp; &nbsp; obj.products.add(product)&nbsp; &nbsp; return JsonResponse({'msg':'Item added to wishlist!'})IMO 更容易,也有助于切换
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python