问题
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'),
    ]
I do not want to set a default value in the author field in the model - it should be user specific.
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.
I think that I need something like https://stackoverflow.com/a/14322706/3960850 but not in Django, but with the Wagtail ModelAdmin.
How to achieve this in Wagtail?
回答1:
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())
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
来源:https://stackoverflow.com/questions/56480823/wagtail-how-to-preopulate-fields-in-admin-form