#name of User foreign key fields to log object creator and last updater
CREATE_USER_FIELD = 'creator'
UPDATE_USER_FIELD = 'updater'

class CreatorUpdaterAdmin(admin.ModelAdmin):
    def save_add(self, request, form, formsets, post_url_continue):
        """
        Set `CREATE_USER_FIELD` to admin user that created the record
        """
        #check main form
        if form.cleaned_data.has_key(CREATE_USER_FIELD):
            form.cleaned_data[CREATE_USER_FIELD] = request.user
            
        #check inlines
        for formset in formsets:
            for cleaned_data in formset.cleaned_data:
                if cleaned_data.has_key(CREATE_USER_FIELD):
                    cleaned_data[CREATE_USER_FIELD] = request.user
        
        return super(CreatorUpdaterAdmin, self).save_add(request, form, formsets, post_url_continue)
    
    def save_change(self, request, form, formsets):
        """
        Set `UPDATE_USER_FIELD` to admin user that updated the record
        """
        #check main form
        if form.cleaned_data.has_key(UPDATE_USER_FIELD):
            form.cleaned_data[UPDATE_USER_FIELD] = request.user
            
        #check inlines
        for formset in formsets:
            for cleaned_data in formset.cleaned_data:
                pk_name = formset.model._meta.pk.attname
                pk_value = cleaned_data.get(pk_name, False)
                #if it doesn't have an primary key value, it is being created
                if not pk_value and cleaned_data.has_key(CREATE_USER_FIELD):
                    cleaned_data[CREATE_USER_FIELD] = request.user
                    
                #inlines get resubmitted on every save, so we need to check if the
                #form differs from the value in the database before setting the
                #UPDATE_USER_FIELD
                elif cleaned_data.has_key(UPDATE_USER_FIELD):
                    model_dict = cleaned_data.copy()
                    del model_dict['DELETE']
                    try:
                        formset.model.objects.get(**model_dict)
                    except formset.model.DoesNotExist:
                        cleaned_data[UPDATE_USER_FIELD] = request.user
        return super(CreatorUpdaterAdmin, self).save_change(request, form, formsets)