如何在Wagtail admin中检索当前用户对象并将其分配给字段?

时间:2019-07-11 15:51:26

标签: django-models wagtail

我使用wagtail的modelAdmin在管理员中显示了一些Django模型。模型中的少数字段引用了用户模型。由于我不是在创建表单/页面,而是通过w来处理的,因此如何在保存当前用户对象时将其传递给该字段?也就是说,创建者和更新者字段应分配有当前用户对象。

请参见下面的代码段,目前我是通过查询来手动分配用户,而我想获得当前用户。

from django.db import models
from django.conf import settings
from django.contrib.auth import get_user_model

from wagtail.admin.forms import WagtailAdminPageForm

STATUS_CHOICES = (
    (1, 'Active'),
    (2, 'Inactive')
)


class BasePageForm(WagtailAdminPageForm):

    def save(self, commit=True):
        auth_user_model = get_user_model()
        default_user = auth_user_model.objects.get(username='admin')
        page = super().save(commit=False)

        if not page.pk:
            page.created_by = default_user
            page.updated_by = default_user
        else:
            page.updated_by = default_user

        if commit:
            page.save()
        return page


class BaseModel(models.Model):
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='created%(app_label)s_%(class)s_related'
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='updated%(app_label)s_%(class)s_related'
    )
    updated_at = models.DateTimeField(auto_now=True)
    status = models.IntegerField(choices=STATUS_CHOICES, default=1)

    class Meta:
        abstract = True  # Set this model as Abstract

    base_form_class = BasePageForm

0 个答案:

没有答案