NoReverseMatch at / Reverse for 'singlepropa' 与参数 '('mens-shirt-1',)' 未找到。已尝试 1 种模式

Posted

技术标签:

【中文标题】NoReverseMatch at / Reverse for \'singlepropa\' 与参数 \'(\'mens-shirt-1\',)\' 未找到。已尝试 1 种模式【英文标题】:NoReverseMatch at / Reverse for 'singlepropa' with arguments '('mens-shirt-1',)' not found. 1 pattern(s) triedNoReverseMatch at / Reverse for 'singlepropa' 与参数 '('mens-shirt-1',)' 未找到。已尝试 1 种模式 【发布时间】:2021-05-13 23:44:30 【问题描述】:

我正在尝试将 2 个参数从 html 标记传递到 django 中的 url。但我收到错误:NoReverseMatch。如果我只传递一个参数,那么它工作正常,但每当我传递 2 个参数时它都会产生错误。我已经阅读了这方面的文档,但我不清楚,我也搜索过这个问题。但没有任何工作。你能帮我弄清楚我该如何解决这个问题吗?

我在html标签中的href是:

<a href='% url "update_cart" slug=product.slug qty=10 %' class="float-right">Add to Cart</a>Add to Cart</a>

我的 urls.py 是:

    urlpatterns = [
    path('', home.Index.as_view(), name='homepage'),
    path('signup', signup.SignUp.as_view(), name="signup"),
    path('login', login.Login.as_view(), name="login"),
    path('logout', login.logout , name="logout"),
    path('basket', basket.Basket.as_view() , name="basket"),
    path('singlepropa/<str:slug>/<int:qty>', singlepropa.SinglePropa.as_view() , name="singlepropa"),
    path('s/', search.Search.as_view() , name="search"),
    path('update_cart/<str:slug>/<int:qty>', basket.update_cart , name="update_cart"),
]

映射url的方法是:

from django.shortcuts import render, redirect, HttpResponseRedirect
from django.views import View
from MStore.models.cartModel import Cart, CartItem
from MStore.models.productModel import ProductModel
from django.urls import reverse

# login class
class Basket(View):

    def get(self, request):
        try:
            the_id = request.session["cart_id"]
        except:
            the_id = None
        if the_id:
            cart = Cart.objects.get(id=the_id)
            context = 'cart': cart
        else:
            empty_msg = "Your Cart is empty. Please keep shopping!"
            context = "empty": True, "empty_msg": empty_msg 

        return render(request, 'basket.html', context)


def update_cart(request, slug, qty):
    try:
        the_id = request.session["cart_id"]
    except:
        new_cart = Cart()
        new_cart.save()
        the_id = new_cart.id
        request.session["cart_id"] = new_cart.id

    cart = Cart.objects.get(id=the_id)
    try:
        product = ProductModel.objects.get(slug=slug)
    except ProductModel.DoesNotExist:
        pass
    except:
        pass
    cart_item, created = CartItem.objects.get_or_create(cart=cart, product=product)
    if created:
        print("Yeah")

    if qty == 0:
        cart_item.delete()
    else:
        cart_item.quantity = qty
        cart_item.save()

    request.session["item_counts"] = cart.cartitem_set.count()

    new_total = 0.00
    for p in cart.cartitem_set.all():
        line_total = float(p.product.price) * p.quantity
        new_total += line_total

    cart.total = round(new_total, 2)
    cart.save()
    return HttpResponseRedirect(reverse("basket"))

我得到的错误:

    NoReverseMatch at /
>     Reverse for 'singlepropa' with arguments '('mens-shirt-1',)' not found. 1 pattern(s) tried:
> ['singlepropa/(?P<slug>[^/]+)/(?P<qty>[0-9]+)$']
>     Request Method:   GET
>     Request URL:  http://127.0.0.1:8000/
>     Django Version:   3.1.5
>     Exception Type:   NoReverseMatch
>     Exception Value:  
>     Reverse for 'singlepropa' with arguments '('mens-shirt-1',)' not found. 1 pattern(s) tried:
> ['singlepropa/(?P<slug>[^/]+)/(?P<qty>[0-9]+)$']
>     Exception Location:   G:\djangoPro\EMart\venv\lib\site-packages\django\urls\resolvers.py,
> line 685, in _reverse_with_prefix
>     Python Executable:    G:\djangoPro\EMart\venv\Scripts\python.exe
>     Python Version:   3.7.3
>     Python Path:  
>     ['G:\\djangoPro\\NShopping',
>      'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
>      'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
>      'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
>      'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32',
>      'G:\\djangoPro\\EMart\\venv',
>      'G:\\djangoPro\\EMart\\venv\\lib\\site-packages']
>     Server time:  Wed, 10 Feb 2021 09:16:40 +0000

完整追溯:

G:\djangoPro\EMart\venv\lib\site-packages\django\core\handlers\exception.py, line 47, in inner
                response = get_response(request) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response
                response = wrapped_callback(request, *callback_args, **callback_kwargs) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\views\generic\base.py, line 70, in view
            return self.dispatch(request, *args, **kwargs) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\views\generic\base.py, line 98, in dispatch
        return handler(request, *args, **kwargs) …
▶ Local vars
G:\djangoPro\NShopping\MStore\views\home.py, line 24, in get
        return render(request, 'index.html', data) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\shortcuts.py, line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\template\loader.py, line 62, in render_to_string
    return template.render(context, request) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\template\backends\django.py, line 61, in render
            return self.template.render(context) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\template\base.py, line 170, in render
                    return self._render(context) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\template\base.py, line 162, in _render
        return self.nodelist.render(context) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\template\base.py, line 938, in render
                bit = node.render_annotated(context) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\template\base.py, line 905, in render_annotated
            return self.render(context) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\template\loader_tags.py, line 150, in render
            return compiled_parent._render(context) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\template\base.py, line 162, in _render
        return self.nodelist.render(context) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\template\base.py, line 938, in render
                bit = node.render_annotated(context) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\template\base.py, line 905, in render_annotated
            return self.render(context) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\template\loader_tags.py, line 62, in render
                result = block.nodelist.render(context) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\template\base.py, line 938, in render
                bit = node.render_annotated(context) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\template\base.py, line 905, in render_annotated
            return self.render(context) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\template\defaulttags.py, line 211, in render
                    nodelist.append(node.render_annotated(context)) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\template\base.py, line 905, in render_annotated
            return self.render(context) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\template\defaulttags.py, line 446, in render
            url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\urls\base.py, line 87, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) …
▶ Local vars
G:\djangoPro\EMart\venv\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix
        raise NoReverseMatch(msg) 

【问题讨论】:

【参考方案1】:

update_cart 只有 1 个参数 product slug。问题出在 singlepropa 网址中。

<a href='% url "update_cart" product.slug %' class="float-right">Add to Cart</a>
<a href='% url "singlepropa" product.slug 10 %' class="float-right">Add to Cart</a>

这将解决您的问题。

https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#url

【讨论】:

感谢@c.grey 的回复,但我已阅读文档,我需要在函数 update_cart(request, slug, qty) 中定义的 singlepropa 中传递两个参数。我已经用 2 个参数更新了 update_cart,我已经尝试了文档中的格式,但它仍然无法正常工作。 @NahidAkhtar 你的 SinglePropa 函数在哪里。 感谢@c.grey 的大力帮助。明白啦。我不应该将它传递给我的 SinglePropa 函数。问题解决了。

以上是关于NoReverseMatch at / Reverse for 'singlepropa' 与参数 '('mens-shirt-1',)' 未找到。已尝试 1 种模式的主要内容,如果未能解决你的问题,请参考以下文章

NoReverseMatch at ...... in django

NoReverseMatch at / posts / post / 18 / comment / Django Error

Django NoReverseMatch at / 路径名和/或顺序是不是冲突?

NoReverseMatch at / Reverse for 'post_detail' 未找到

NoReverseMatch at /accounts/password-reset/ 用于 Django 中的密码重置

NoReverseMatch at / Reverse for 'singlepropa' 与参数 '('mens-shirt-1',)' 未找到。已尝试 1 种模式