Django - Accessing _set from Admin change page

丶灬走出姿态 提交于 2019-12-25 02:14:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!