django admin 中用户定义的文本字段
Django(和数据库)新手在这里。
我正在尝试找出一种方法来使用管理界面为表(我们称之为“书”)创建 n 个自定义文本字段。我想要一种让用户通过管理界面定义新文本字段的方法(而不是通过模型定义 CustomField1、CustomField2 等字段,然后运行 manage.pysyncdb)。
最终,我想创建一个名为 CustomFields 的单独表。 django 管理员用户(不是程序员)将进入此表中的自定义文本字段(例如 pubdate、isbn、国家/地区)。然后,在为书籍进行数据输入时,他们会为所需的每个自定义字段点击“+”,将它们显示在下拉列表中,并为自定义字段添加随附文本。为每个字段输入的文本特定于父图书。
有什么建议吗?我有一种感觉,有一个简单的解决方案,但我在这里没有掌握。
Django (and database) newbie here.
I'm trying to figure out a way to enable the creation of n custom text fields for a table (let's call it Book) using the admin interface. I would like a way for the user to define new text fields through the admin interface (instead of defining fields like CustomField1, CustomField2, etc, through a model followed by running manage.py syncdb).
Ultimately, I would want to create a separate table called CustomFields. The django admin user (who is not a programmer), would go and enter the custom text fields in this table (e.g. pubdate, isbn, country). Then, when doing data entry for a Book, they would hit "+" for every custom field they wanted, have them available in a dropdown, and add accompanying text for the custom field. The text entered for each field is specific to the parent Book.
Any suggestions? I have a feeling there's a simple solution that I'm somehow not grasping here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能会遇到问题的地方是因为 Django 不会根据更改的模型声明重新创建表或列。这意味着如果不在数据库上手动运行生成的 sql,则无法在运行时将字段添加到表中。相反,您需要的是一种定义自定义字段并将它们链接到您的模型的方法。
我的建议如下:
上面的验证是相当不存在的,这不允许您为每个模型定义所需的自定义字段,但如果您需要,您应该能够提出该部分稍后再说。
这将允许用户直接选择最多 3 个自定义字段和值,并且可以根据需要选择添加更多字段和值。
编辑:更改了答案以反映评论中的更多信息。
Where you might run into problems is because Django will not recreate tables or columns based on changing model declarations. This means you're unable to add fields to a table at run-time without running the generated sql on your database manually. What you'll need, instead, is a way of defining custom fields, and linking them to your model.
What I'd suggest is the following:
The validation on the above is fairly non-existant, and this doesn't allow you to define required custom fields for each model, but you should be able to come up with that part if you need it later on.
This will allow users to select up to 3 custom fields and values directly, with the option to add more if they wish.
Edit: Changed the answer to reflect further information in comments.
一开始,您可以为书籍创建一个模型,为文本字段创建一个模型,两者都通过 外键关系。然后您可以通过 django 的内联管理员轻松管理它,这将使您能够添加更多文本字段!
For the beginning you can create one model for the book and one for the text field, both connected through a foreign key relation. You can easily administrate this then through django's inline admins, which will enable you to add more text fields!