Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: How to hook save button for Model admin?

I have a Model with a "status" field. When the user users the Admin app to modify an instance, how to I hook onto the "Save" button click so that I could update "status" to a value that's dependent on the logged in user's username?

like image 245
zer0stimulus Avatar asked Sep 05 '10 16:09

zer0stimulus


2 Answers

Override your modeladmin's save_model-method:

class ModelAdmin(admin.ModelAdmin):       
    def save_model(self, request, obj, form, change):
        user = request.user 
        instance = form.save(commit=False)
        if not change:    # new object
            instance.status = ....
        else:             # updated old object
            instance.status = ...
        instance.save()
        form.save_m2m()
        return instance
like image 133
Bernhard Vallant Avatar answered Sep 29 '22 15:09

Bernhard Vallant


Use the pre_save signal. Granted, it will be called on every instance save operation, not only from admin, but it does apply to your situation.

like image 41
Yuval Adam Avatar answered Sep 29 '22 14:09

Yuval Adam