使模型中的用户默认为当前用户

2022-01-25 00:00:00 python django django-models django-admin

问题描述

我有以下几点:

from django.contrib.auth.models import User

class ClientDetails(models.Model):
    created_by = models.ForeignKey(User)
    ...

如何让 created_by 默认为当前登录的用户?

How do I make created_by default to the currently logged in user?

(我想这样做是为了可以将它隐藏在管理视图中,主要是因为当我保存一个实例时,我不想每次都填充它)


解决方案

由于需要从 request 对象中获取当前登录的用户,因此无法在模型的 save-方法,但您可以例如覆盖模型管理员的 save_model-方法:

Since you need to get the currently logged in user from a request object you cannot get it in the model's save-method,but you can eg override the model admin's save_model-method:

class MyAdmin(admin.ModelAdmin):
    def save_model(self, request, instance, form, change):
        user = request.user 
        instance = form.save(commit=False)
        if not change or not instance.created_by:
            instance.created_by = user
        instance.modified_by = user
        instance.save()
        form.save_m2m()
        return instance

相关文章