标准示例:
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 ...
我想在Book
更改页面中修改Author
我尝试使用InlineModelAdmin,但由于Book
有很多字段,因此编辑起来并不容易
这就是为什么我试图将链接指向作者/更改模板上的 children 。
<ul>
<li><a href="{% url admin:content_scribpart_add %}">Add a Book</a></li>
{% for book in original.book_set.all %}
<li><a href="{% url admin:myapp_book_change book.id %}">Edit {{ book }}</a></li>
{% endfor %}
</ul>
但是有几个问题
Author
表单Book
ID
Author
答案 0 :(得分:4)
是的,当然。
将author
主键作为GET
参数附加到您的网址:
<ul>
<li><a href="{% url admin:content_scribpart_add %}?author={{ object_id }}">Add a Book</a></li>
{% for book in original.book_set.all %}
<li><a href="{% url admin:myapp_book_change book.id %}?author={{ object_id }}">Edit {{ book }}</a></li>
{% endfor %}
</ul>
修改相应的ModealAdmin
图书,覆盖response_add()
and response_change()
。请注意,我们还override formfield_for_forein_key
以预先填充author
字段:
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
class BookAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "author":
try:
author_pk = int(request.GET.get('author', ''),)
except ValueError:
pass
else:
kwargs["initial"] = Author.objects.get(pk=author_pk)
return super(BookAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
def response_add(self, request, obj, post_url_continue=None):
return HttpResponseRedirect(reverse('admin:myapp_author_change', args=(obj.author.pk,))
)
def response_change(self, request, obj, post_url_continue=None):
return HttpResponseRedirect(reverse('admin:myapp_author_change', args=(obj.author.pk,))
)