问题
Lets take the standard example
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author)
#... Many other fields ...
From the admin change template of Author
trying to access to the related books
<ul>
{% for book in original.book_set.all %}
<li>
<a href="{% url admin:myapp_manager_change book.id %}">Edit {{ book }}</a>
</li>
{% endfor %}
</ul>
I get
Caught NoReverseMatch while rendering: Reverse for 'myapp_manager_change' with arguments '(1L,)' and keyword arguments '{}' not found.
Why ?
And how can I access this book_set
?
回答1:
Check the docs on reversing admin urls.
You have to replace "myapp" with your actual app:
admin:{{ app_label }}_{{ model_name }}_change object_id
So if your app is named library and your model's name is book the link would be:
<a href="{% url admin:library_book_change book.id %}">Edit {{ book }}</a>
回答2:
book_set actually works well in your example because the exception is raised from inside the
for
loop. It seems the problem is with the view name.
Try this:
{% url admin:myapp_book_change book.id %}
来源:https://stackoverflow.com/questions/8051535/django-accessing-set-from-admin-change-page