【问题标题】:Django - Admin : Editing child model without inlineFormDjango - 管理员:编辑没有 inlineForm 的子模型
【发布时间】:2011-11-09 11:25:21
【问题描述】:

标准示例:

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 ...

我想从 Author 更改页面编辑 Books。
我尝试使用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>

但是有几个问题

  • 如何在Book 表单中预填充相关的Author id
  • 如何让保存按钮返回到相关的Author
  • 我在正确的轨道上吗?

【问题讨论】:

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


    【解决方案1】:

    是的,当然。

    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. 修改book对应的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,))
              )
      

    【讨论】:

    • Author.objects.filter(pk=author_pk) 过滤选择框但不预先填充
    • 最后我将使用kwargs["initial"] = Author.objects.get(pk=author_pk)而不是kwargs["queryset"] = Author.objects.filter(pk=author_pk)
    • 也是admin:myapp_author_change而不是admin_myapp_author_change
    猜你喜欢
    • 2010-11-25
    • 2011-09-28
    • 2012-07-18
    • 2018-11-27
    • 2023-03-14
    • 2018-11-30
    • 1970-01-01
    • 2021-12-11
    • 2015-04-26
    相关资源
    最近更新 更多