g-如何预先填充管理表单中的字段? [英] Wagtail - how to preopulate fields in admin form?

查看:36
本文介绍了g-如何预先填充管理表单中的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想预先在Wagtail页面管理员中填充字段.特别是我想使用当前登录的管理员/编辑用户的用户名,并将其作为字符串填写在表单中.我的页面的简化版本如下所示:

I would like to pre-populate fields in wagtail page admin. Particularly I would like to take username of currently logged admin/editor user and fill it in the form as a string. A simplified version of my page looks like this:

class ItemPage(Page):

    author = models.CharField(max_length=255, default="")

    content_panels = Page.content_panels + [
        FieldPanel('author'),
    ]

我不想在模型的author字段中设置默认值-它应该是用户特定的.

I do not want to set a default value in the author field in the model - it should be user specific.

在保存/更改模型后,我不想使用 save 方法或信号.用户应该看到那里有什么并且应该有能力对其进行更改.另外,页面将在没有管理界面的情况下自动生成.

I do not want to use the save method or signal after the model is saved/altered. The user should see what is there and should have the ability to change it. Also, the pages will be generated automatically without the admin interface.

我认为我需要类似 https://stackoverflow.com/a/14322706/3960850 之类的东西,但不需要Django,但使用Wagtail ModelAdmin.

I think that I need something like https://stackoverflow.com/a/14322706/3960850 but not in Django, but with the Wagtail ModelAdmin.

如何在Wa中实现这一目标?

How to achieve this in Wagtail?

推荐答案

下面是一个基于gasmans注释和他们链接的新代码随附的文档的示例:

Here is an example based on gasmans comment and the documentation that accompanies the new code they linked:

from wagtail.admin.views.pages import CreatePageView, register_create_page_view
from myapp.models import ItemPage

class ItemPageCreateView(CreatePageView):
    def get_page_instance(self):
        page = super().get_page_instance()
        page.author = 'Some default value'
        return page

register_create_page_view(ItemPage, ItemPageCreateView.as_view())

您也可以通过覆盖模型的 init 方法来执行此操作,但是上面的方法要好得多

You could also do this by overriding the models init method, but the above is much nicer

class ItemPage(Page):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        try:
            author = kwargs['owner'].username
        except (AttributeError, KeyError):
            pass
        else:
            self.author = author

这篇关于g-如何预先填充管理表单中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆