Django admin:带有 2 个外键的 Many2Many 模型的内联
经过几天的绞尽脑汁,我只是希望有人能指出我正确的方法。 我有 4 个模型:页面、元素、样式和帖子。
这是我的 simplefied models.py/admin.py 摘录: http://pastebin.com/uSHrG0p2
两句话:
一个元素引用 1 个样式和 1 个帖子(2 个 FK)。
一个页面可以引用许多元素,元素可以被许多页面引用(M2M)。
在页面实例的管理站点上,我将 M2M 关系包含为“内联”。这样我就有多行来选择元素实例。 一行看起来像:[我的帖子 A 和我的风格 X][V]
我想要的是将那个下拉菜单替换为 2 个下拉菜单。一种包含所有 Post 实例,另一种包含所有 Style 实例(就地创建 Element 实例)。因此,这一行看起来类似于 Element 管理站点: [My Post A][V] [My Style X][V]
听起来很简单,但在使用 ModelForms、ModelAdmins 阅读和试验 2 天后我完全迷失了方向, 表单集, ... . 我可以在 Django 管理功能中不使用自定义视图/表单来做到这一点吗?
我的方法之一是从这样的 PageAdminForm 访问 Post/Style 实例,尝试从中手动创建表单小部件...但未能这样做:
p = Page.objects.get(pk=1)
f = PageAdminForm(instance=p)
f.base_fields['elements'].choices.queryset[0].post
有什么建议或提示我需要走哪条路吗? 谢谢您的宝贵时间!
after wracking my brain for days, I just hope someone can point me to the right approach.
I have 4 Models: Page, Element, Style and Post.
Here is my simplyfied models.py/admin.py excerpt: http://pastebin.com/uSHrG0p2
In 2 sentences:
A Element references 1 Style and 1 Post (2 FKs).
A Page can reference many Elements, Elements can be referenced by many pages (M2M).
On the admin site for Page instances I included the M2M relation as 'inline'. So that I have multiple rows to select Element-instances.
One row looking like: [My Post A with My Style X][V]
What I want is to replace that one dropdown with 2 dropdowns. One with all instances of Post and one with all instances of Style (creating Element instances in-place). So that one row would look similar to the Element admin site: [My Post A][V] [My Style X][V]
Sounds easy, but I'm just completely lost after reading and experimenting for 2 days with ModelForms, ModelAdmins, Formsets, ... .
Can I do that without custom views/forms within the Django admin functionality?
One of my approaches was to access the Post/Style instances from a PageAdminForm like this, trying to create a form widget manually from it... but failed to do so:
p = Page.objects.get(pk=1)
f = PageAdminForm(instance=p)
f.base_fields['elements'].choices.queryset[0].post
Any advice or hint which way I need to go?
Thank you for your time!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在删除 M2M 字段并将 Elements 链接到具有 Element 中的第三个外键的页面后,我得到了我想要的结果:
实际上,非 M2M 链接毕竟对我的应用程序更有意义。
自我备忘录:在试图智胜 Django 之前重新思考模型关系:-(
I got exactly what I wanted after removing the M2M field and linking Elements to a Page with a 3rd ForeignKey in Element:
Actually a non-M2M link makes more sense for my application after all.
Memo to self: Rethink model relations before trying to outsmart Django :-(