Django - 管理员:编辑没有inlineForm的子模型

时间:2011-11-09 11:25:21

标签: django django-models django-admin parent-child

标准示例:

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
  • 我是在正确的轨道上吗?

1 个答案:

答案 0 :(得分:4)

是的,当然。

  1. 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>
    
  2. 修改相应的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,))
            )