1
votes

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
FWIW, we had a similar requirement and found that there wasn't a good way to hook into Wagtail's 'create page' view to achieve this. I've now opened a pull request github.com/wagtail/wagtail/pull/5353 to support this, which will hopefully make it into a future release. - gasman

1 Answers

3
votes

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