python - “/”处的 NoReverseMatch
问题描述
您好,我收到错误“NoReverseMatch at”/”当我将 HTML 模板更改为 {% url 'cart-page' cart.id %},当我使用 user.username 时,一切正常,但我想要一个购物车.id 代替用户名。这不是 urls.py 的错,因为我已将 int 更改为 str ,反之亦然。
代码:
HTML:
<div class="navbar__rightside">
<a class="navbar__link" href="{% url 'cart-page' cart.id %}">Cart</a>
<a class= "navbar__link" href="{% url 'profile-page' user.username %}">Profile</a>
<a class="navbar__link" href="{% url 'logout-page' %}">Logout</a>
</div>
视图.py:
class ShopListView(ListView):
model = Item
template_name = 'shop/home.html'
context_object_name = 'items'
def post(self, request, *args, **kwargs):
return reverse('detail-page')
class CartView(TemplateView):
template_name = "shop/cart.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['cart'] = Cart.objects.annotate(
price=Sum(F('orderitem__item__price') * F('orderitem__quantity'))
).get(order_user= self.request.user)
cart = context['cart']
cart.total = cart.price
cart.save()
context['order_items'] = OrderItem.objects.filter(cart=cart)
return context
def post(self, request, pk):
if 'minus' in request.POST:
cart = Cart.objects.get(order_user=self.request.user)
OrderItem.objects.filter(id=pk, cart=cart).update(
quantity=F('quantity')-1)
return HttpResponse("cart uptaded")
网址.py
path('', ShopListView.as_view(), name='home-page'),
path('cart/<int:pk>/', CartView.as_view(), name='cart-page'),
解决方案
在你的 html
<div class="navbar__rightside">
<a class="navbar__link" href="{% url 'cart-page' pk=cart.id %}">Cart</a>
<a class= "navbar__link" href="{% url 'profile-page' user.username %}">Profile</a>
<a class="navbar__link" href="{% url 'logout-page' %}">Logout</a>
</div>
你必须告诉我你指的是什么 id 并告诉我是否仍然不适合你
推荐阅读
- javascript - 导入模块时无法在模块外使用导入语句
- asp.net-core - 在 adomd.net 中的两个表之间创建关系
- javascript - 为什么 prettier 将尾随逗号放在自己的位置并给出错误说它需要删除?
- flutter - ListView.builder 在列内不起作用
- liferay - 如何将表的名称和id字段绑定到liferay中的下拉列表
- django - 如何仅在分页查询集结果上运行 SearchHeadline(一个繁重的功能)
- azure - Azure DevOps 中的发布管道成功,打开 URL 时,页面为空白
- python - 在 3 种颜色之间随机更改新像素,在每个像素上随机更改
- java - 从android studio创建一个阅读应用程序我想在用户点击它时将作为书籍文件的搜索项放到阅读栏?
- html - 为什么只有 nunjucks 在 url 中循环创建的第一个按钮的值?