matousc
matousc

Reputation: 3977

Wagtail - how to preopulate fields in admin form?

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?

Upvotes: 2

Views: 1708

Answers (2)

Paul
Paul

Reputation: 45

I wanted to do something similar and found out, how to do it.

Task There is a blog (build with Wagtail) allowing multiple article authors. An article page also exposes details of the author (profile picture, job, introduction of the author) who wrote an article.

Solution So extend the default user model with the fields which should be added

https://docs.wagtail.org/en/stable/advanced_topics/customisation/custom_user_models.html

and access the user in the template (through owner).

https://docs.wagtail.org/en/stable/reference/pages/model_reference.html#wagtail.models.Page.owner

Upvotes: 0

user3365957
user3365957

Reputation: 308

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

Upvotes: 3

Related Questions