Django:如何在管理中显示文本字段之前修改它
我有一个带有文本字段的 Django 模型。我想在 Django Admin 中将文本字段的内容呈现给用户之前修改它。
我期望看到相当于 post_load 的信号,但它似乎不存在。
更具体地说:
我有一个接受用户输入的文本字段。在此文本字段中有一个阅读更多分隔符。分隔符之前的文本将进入 introtext 字段,之后的所有内容都会进入 fulltext 字段。
同时,我只想在用户 1 编辑文章时显示他们的文本字段。
我的计划是 on_load 从 introtext 和 fulltext 字段读取数据并将它们组合到全文文本区域中。在 pre_save 上,我将使用“阅读更多”分隔符分割文本,并将介绍存储在 introtext 中,将剩余部分存储在全文中。
因此,在显示表单之前,我需要填充全文字段,
introtext + '<!--readmore-->' + fulltext
并且我需要能够对现有项目执行此操作。
I have a Django Model with a text field. I would like to modify the content of the text field before it's presented to the user in Django Admin.
I was expecting to see signal equivalent of post_load but it doesn't seem to exist.
To be more specific:
I have a text field that takes user input. In this text field there is a read more separator. Text before the separator is going to go into introtext field, everything after goes into fulltext field.
At the same time, I only want to show the user 1 text field when they're editing the article.
My plan was to on_load read the data from introtext and fulltext field and combine them into fulltext textarea. On pre_save, I would split the text using the read more separator and store intro in introtext and remainder in fulltext.
So, before the form is displayed, I need to populate the fulltext field with
introtext + '<!--readmore-->' + fulltext
and I need to be able to do this for existing items.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 提供您自己的管理页面的表单。
一旦你有了自己的表单,你就可以使用表单中的默认参数来提供你想要的初始值。请参阅表单字段的 初始参数 上的文档。正如此链接将向您展示的那样,可以使用可调用或常量作为初始值。
Have a look into Providing your own form for the admin pages.
Once you have your own form, you can use the default param in the form to provide the initial value you want. See the docs on the Initial param for the form field. As this link will show you, it is possible to use a callable or a constant as your initial value.
没有post_load,因为没有load函数。
实例的加载是在 init 函数中完成的,因此正确的答案是使用 post_init 信号。
There is no post_load because there is no load function.
Loading of the instance is done in init function, therefore the right answer is to use post_init signal.