我有一个由查询集对象组成的链接列表。点击每个链接应该带我到该对象的详细视图。但我收到以下错误:
NoReverseMatch at /idea_tracker/shoppinglist/
Reverse for 'views.recipient_detail' not found. 'views.recipient_detail' is not a valid view function or pattern name.
我的模特:
class Recipient(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
birthday = models.CharField(max_length=10, blank=True)
notes = models.TextField(max_length=255, blank=True)
def __str__(self):
return "{} {}".format(self.first_name, self.last_name)
def get_absolute_url(self):
return reverse(
'views.recipient_detail',
args=(),
kwargs={'recipient_id': str(self.id)}
)
class Gift(models.Model):
name = models.CharField(max_length=30, blank=True)
model_number = models.CharField(max_length=30, blank=True)
price = models.DecimalField(default=0.00, decimal_places=2,
max_digits=6)
recipients = models.ManyToManyField(Recipient, blank=True)
purchased = models.BooleanField(default=False)
def __str__(self):
return "{}".format(self.name)
我的观点:
def shopping_list(request):
recipients =
models.Recipient.objects.prefetch_related('gift_set').\
all().order_by('last_name')
gift_list = models.Gift.objects.all()
total = []
for y in gift_list:
total.append(y.price)
total_price = sum(total)
return render(request, 'idea_tracker/shoppinglist.html', {
'recipients': recipients,
'total_price': total_price
})
def recipient_detail(request, pk):
recipient = get_object_or_404(models.Recipient, pk=pk)
gift = recipient.gift_set
return render(request, 'idea_tracker/recipient_detail.html', {
'recipient': recipient
})
我的网址:
urlpatterns = [
url(r'^shoppinglist/', views.shopping_list, name='shopping_list'),
url(r'^recipient_detail/(?P<recipient_id>)/$',
views.recipient_detail, name='recipient_detail'),
]
我的模板:
<h3> Click on a Recipient to edit or delete:</h3>
{% for name in recipients %}
<ul>
<li><a href="{{ name.get_absolute_url }}">{{ name.first_name }}
{{ name.last_name }} /
{% for gift in name.gift_set.all %}
<span style='color:darkblue'>{{ gift }}</span></a></li>
{% endfor %}
</ul>
{% endfor %}
答案 0 :(得分:2)
您应该使用网址格式recipient_detail
的名称:
return reverse(
'recipient_detail',
args=(),
kwargs={'recipient_id': str(self.id)}
)
您的recipient_id
群组为空。例如,您可以将数字与:
url(r'^recipient_detail/(?P<recipient_id>\d+)/$',
views.recipient_detail, name='recipient_detail'),
最后,您应该在pk
视图中将recipient_id
更改为recipient_detail
以匹配网址格式。