我如何解决 'Add' 的 Reverse 问题,但未找到参数“(”,)'。尝试了 1 种模式:['agregar/(?P<producto_id>[0-9]+)/\Z'] 错误?

how can i solve Reverse for 'Add' with arguments '('',)' not found. 1 pattern(s) tried: ['agregar/(?P<producto_id>[0-9]+)/\\Z'] error?

我正在做 django 的教程,我在尝试添加 href 按钮时遇到此错误,我使用的是 django 4.0.4 版本和 python 3.9 版本。

Models.py

class Producto(models.Model):
    serie_producto = models.CharField(max_length=30)
    nombre = models.CharField(max_length=30)
    codigo = models.CharField(max_length=15)
    marca = models.CharField(max_length=30)
    precio = models.IntegerField()
    created_date = models.DateTimeField(default=timezone.now)

urls.py

...
urlpatterns = [
    ...
    path('agregar/<int:producto_id>/', agregar_producto, name="Add"),
    ...

]

导致错误的模板目录。消息错误突出显示 {% url 'Add' producto.id %}

{% for producto in response %}
          <div class="col-6">
            <div class="card" style="height: 10rem; width: 23rem; margin: 5px 0px;">
              <div class="card-body">
                <h5 class="card-tittle">{{producto.nombre}}</h5>
                <p class="card-text">{{producto.marca}}</p>
                <p class="card-text">{{producto.precio}}</p>
                <a href="{% url 'Add' producto.id %}" class="btn btn-primary">Agregar al carrito</a>
              </div>
            </div>
          </div>
          {% endfor %}

view.py

from tienda.models import Producto
from tienda.carrito import Carrito
def catalogo(request):
    url = "http://127.0.0.1:8000/api/Producto/"
    response = requests.get(url, auth=('admin','duoc'))
    datos = response.json()
    return render(request, 'catalogo.html', {'response' : datos })

def agregar_producto(request, producto_id):
    carrito = Carrito(request)
    producto = Producto.objects.get(id=producto_id)
    carrito.agregar(producto)
    return redirect("Tienda")

问题 当我进入目录模板时,我得到了前面提到的错误,当我不使用 {% url 'Add' producto.id %} 时,api 工作正常,我认为是有 id 的东西,可能看不懂??,我不知道是不是这个。我不知道如何解决这个问题或出了什么问题。

我该如何解决这个问题?

欢迎任何建议或帮助。

编辑:

来自 cmd 的完整错误消息:

File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\giova\Desktop\Pagina-Web-Django-con-Api\tienda\views.py", line 17, in catalogo
    return render(request, 'catalogo.html', {'response' : datos })
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\shortcuts.py", line 24, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\backends\django.py", line 62, in render
    return self.template.render(context)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 175, in render
    return self._render(context)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 167, in _render
    return self.nodelist.render(context)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 1000, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 1000, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 958, in render_annotated
    return self.render(context)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\defaulttags.py", line 238, in render
    nodelist.append(node.render_annotated(context))
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 958, in render_annotated
    return self.render(context)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\defaulttags.py", line 472, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\base.py", line 88, in reverse
    return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
  File "C:\Users\giova\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 802, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'Add' with arguments '('',)' not found. 1 pattern(s) tried: ['agregar/(?P<producto_id>[0-9]+)/\Z']

好吧,伙计们,我刚刚找到了我的问题的错误,我要去 post 这里为其他有同样问题的人。

在我的序列化程序中,我没有指定 'id'

class ProductoSerializer(serializers.HyperlinkedModelSerializer) :
class Meta:
    model = Producto
    fields = ['url', 'nombre', 'codigo', 'precio', 'serie_producto', 'marca']

soo,解决办法是:

class ProductoSerializer(serializers.HyperlinkedModelSerializer) :
class Meta:
    model = Producto
    fields = ['id' #here ,'url', 'nombre', 'codigo', 'precio', 'serie_producto', 'marca']
django.urls.exceptions.NoReverseMatch: Reverse for 'Add' with arguments '('',)' not found. 1 pattern(s) tried: ['agregar/(?P<producto_id>[0-9]+)/\Z']

此错误告诉您名称为 'Add' 的视图需要一个整数参数,但您向它传递了一个空字符串 ''。要对此进行调试,您可以在 render() 调用之前添加 print(datos)。您很可能会看到 JSON 个对象的列表,其中至少有一个 id: "".