How can I access request object in the wagtail Page model?

大兔子大兔子 提交于 2019-12-08 04:12:57

问题


I wanna dynamically set default value of the field to the currently logged in user:

class SimplePage(Page):
    author = models.CharField(max_length=255, default=request.user)

I know about get_context, but class attributes cannot call instance methods.

def get_context(self, request, *args, **kwargs):
    return {
        PAGE_TEMPLATE_VAR: self,
        'self': self,
        'request': request,
    }

Any more ideas?

Essentially whoever is logged in into the admin should become author's default.


回答1:


I got part way there but am not sure how to get the request context for the admin forms generated by the Wagtail edit_handler system.

Overview

  • Wagtail lets you set a custom form for use within its admin, we do this by adding base_form_class to the page model, which will reference a new class that extends WagtailAdminPageForm.
  • We then provide initial values to the form by passing in an initial object to the super class's __init__.
  • To get the auth model (for both relating it to the SimplePage model and when getting a default value we use Django's builtin auth/user helpers.

Example

Note: Using Wagtail 2.0 import syntax.

from django.conf import settings
from django.contrib.auth import get_user_model
from wagtail.wagtailadmin.forms import WagtailAdminPageForm
#... other imports you should already have


class SimplePageForm(WagtailAdminPageForm):

    def __init__(self, *args, **kwargs):
        auth_user_model = get_user_model()
        default_user = auth_user_model.objects.get(username='admin')
        initial = {
            'title': 'Unhelpful default title for the sake of example',
            'author_user': default_user
        }
        super().__init__(initial=initial, *args, **kwargs)


class SimplePage(Page):

    author_user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.PROTECT
    )

    content_panels = Page.content_panels + [FieldPanel('author_user')]

    base_form_class = SimplePageForm


来源:https://stackoverflow.com/questions/48686930/how-can-i-access-request-object-in-the-wagtail-page-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!