django admin添加数据自动记录user到表中的实现方法

1.需求:在后台添加一条数据的同时要把添加者记录到表中。

2.models.py

class Setting(models.Model): 
  ...      
  user = models.CharField(max_length=50, blank=True, help_text=u"添加者")
  ...

3.admin.py

@register(Setting)
class SettingAdmin(admin.ModelAdmin):
  list_display = ("pk", "user", "other_field")
  def save_model(self, request, obj, form, change):
    obj.user = request.user
    obj.save()
  readonly_fields = ("user", )

相关推荐