zer0stimulus
zer0stimulus

Reputation: 23606

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?

Upvotes: 8

Views: 4793

Answers (4)

MarekDev
MarekDev

Reputation: 21

form.cleaned_data.get('categories')

This gets the value directly in the ModelAdmin.save_model

Upvotes: 0

Bernhard Vallant
Bernhard Vallant

Reputation: 50776

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

Upvotes: 17

zer0stimulus
zer0stimulus

Reputation: 23606

ModelAdmin.save_model() provides just what I need

Upvotes: 4

Yuval Adam
Yuval Adam

Reputation: 165232

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.

Upvotes: 6

Related Questions