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

时间:2015-07-12 10:19:36

标签: python django admin

我有一个带字段的模型:

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

在我的管理员中:

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

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

我该怎么做?

谢谢

2 个答案:

答案 0 :(得分:7)

您已经设置了How to: Use a Background Worker,因此created_by不会出现在Django管理员的表单中。

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

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()

答案 1 :(得分:0)

为此,请覆盖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()