我正在参加初学者
Django
课程,但我无法修复视图和产品链接
NoReverseMatch at / Reverse for 'produto' with arguments '(1,)' not found. 1 pattern(s) tried: ['produto/<int:pk\\Z']
我真的不知道该怎么做才能解决这个问题。
索引文件:
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Django 1 - Index</title>
</head>
<body>
<h2>{{curso}}</h2>
<h1>index</h1>
<table>
<thead>
<tr>
<th>Produto</th>
<th>Preço</th>
</tr>
</thead>
<tbody>
{% for produto in produtos %}
<tr>
<td><a href="{% url 'produto' produto.id %}">{{produto.nome}}</a></td>
<td>{{produto.preco}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
视图:
from django.shortcuts import render
from .models import Produto
def index(request):
produtos = Produto.objects.all()
context = {
'curso': 'Programação web com django',
'produtos': produtos
}
return render(request, 'index.html', context)
def contato(request):
return render(request, 'contato.html')
def produto(request, pk):
prod = Produto.objects.get(id=pk)
context = {
'produto': prod
}
return render(request, 'produto.html')
produto.html 文件:
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Produto</title>
</head>
<body>
<h1>Produto</h1>
<table>
<thead>
<tr>
<th>Produto</th>
<th>Preço</th>
<th>Estoque</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="{% url 'index' %}">{{produto.nome}}</a></td>
<td>{{produto.preco}}</td>
<td>{{produto.estoque}}</td>
</tr>
</tbody>
</table>
</body>
</html>
错误信息:
我已经尝试将
pk
更改为id
,但没有解决。
from django.urls import path
from .views import index, contato, produto
urlpatterns = [
path('', index, name='index'),
path('contato/', contato, name='contato'),
path('produto/<int:pk>/', produto, name='produto'),
]
这可以帮助你。只需要关闭 urls.py 中的尖括号。
需要更改索引中的标签,应该是:
<a href="{% url 'produto' produto.pk %}">
还要确保您的网址是正确的,如下所示:
from django.urls import path
from .views import index, contato, produto
app_name = 'djangoappname'
urlpatterns = [
path('', index, name='index'),
path('contato/', contato, name='contato'),
path('produto/<int:pk>/', produto, name='produto'),
]