[Django]-Auto-populating created_by field with Django admin site

33👍

http://code.djangoproject.com/wiki/CookBookNewformsAdminAndUser

Involves implementing save methods on your ModelAdmin objects.

👤jsamsa

4👍

You need to specify a default for the field, in this case a method call that gets the current user (see the auth documentation to get the current user).

2👍

I did it by overriding the save_model method in django admin. Since you mentioned that you wanted to use the Django admin interface. So, I think my solution will be the most appropriate one. The solution goes like this:

  1. First register the Contact model in the admin by excluding the ‘created_by’ field
@admin.register(Contact)
class Notice(admin.ModelAdmin):
    list_display = ('name', 'created_by')
    exclude = ('created_by', )
  1. Then override the save_model method in the same class Notice
def save_model(self, request, obj, form, change,):
    obj.created_by = request.user

    super().save_model(request, obj, form, change)

1👍

I really wanted a better solution than the ones I found elsewhere, so I wrote some middleware – implementation on the Populate user Id question. My solution requires no changes to any form or view.

Leave a comment