h3.
h3.

Reputation: 11068

Auto-populating created_by field with Django admin site

I want to use the Django admin interface for a very simple web application but I can't get around a problem that should not be that hard to resolve ..

Consider the following:

class Contact(models.Model):
    name = models.CharField(max_length=250, blank=False)
    created_by = models.ForeignKey(User, blank=False)

I can't find a way to auto-populate the created_by field and make the Django admin aware of it. Most of the method I've seen implies overloading the Object's save method and pass it the request user. They all requires to build your custom views and/or forms.

Optimally the form to create new contacts in the admin site should not show the created_by field (which is quite easy) and auto-populate it with the current user (which seems harder than it should).

Upvotes: 30

Views: 28936

Answers (4)

Nabajyoti Das
Nabajyoti Das

Reputation: 524

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)

Upvotes: 3

mindlace
mindlace

Reputation: 303

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.

Upvotes: 1

Tom Leys
Tom Leys

Reputation: 19029

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

Upvotes: 4

jsamsa
jsamsa

Reputation: 969

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

Involves implementing save methods on your ModelAdmin objects.

Upvotes: 35

Related Questions