Django 管理模型字段设置为当前用户

Django admin model field set to current user

我有一个带有字段的模型:

class MyModel(models.Model):
    name = models.CharField(max_length=50)
    created_by = models.ForeignKeyField(User)

在我的管理员中:

class MyModelAdmin(admin.ModelAdmin):
    list_display= ("name",)
    fields = ("name",)

这里我不想 created_by 在管理员中添加 MyModel。我希望将其设置为当前用户,例如 created_by = request.user

我该怎么做?

谢谢

您已经设置 fields 以便 created_by 不会出现在 Django 管理的表单中。

现在您需要覆盖 save_model,并在保存新对象之前设置用户。

class MyModelAdmin(admin.ModelAdmin):
    fields = ("name",)

    def save_model(self, request, obj, form, change):
        if not change:
            # the object is being created, so set the user
            obj.created_by = request.user
        obj.save()

为此覆盖 save_model 方法并将 created_by 字段设置为当前用户。

class MyModelAdmin(admin.ModelAdmin):
    list_display= ("name",)
    fields = ("name",)

    def save_model(self, request, obj, form, change):             
        if not change: 
        # can use this condition also to set 'created_by'    
        # if not getattr(obj, 'created_by', None):            
            obj.created_by = request.user
        obj.save()