gpt4 book ai didi

Django-管理员 : Editing child model without inlineForm

转载 作者:行者123 更新时间:2023-12-02 04:30:44 26 4
gpt4 key购买 nike

标准示例:

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

我想从作者更改页面编辑书籍
我尝试过 InlineModelAdmin但由于 Book 字段较多,编辑起来并不容易。
这就是为什么我尝试在作者/更改模板上添加指向 child 的链接。

<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 表单中预填充相关的作者 ID
  • 如何使用“保存”按钮返回到相关的作者
  • 我走在正确的道路上吗?

最佳答案

是的,当然。

  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,))
    )

关于Django-管理员 : Editing child model without inlineForm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8064325/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com