Reputation: 596
I'd like to customize my django admin actions. My goal is to make a action that could update selected objects, but there is not only one model or one field to be updated. So I guess I should write more than one actions, though these code are quite similar. My question is how to write these actions, considering code reuse.
For example, function update_module(modeladmin, request, queryset) implements a action as below,
def update_module(modeladmin, request, queryset):
...
form = module_form(request.POST)
if form.is_valid():
one = form.cleaned_data['module']
...
....
admin.site.add_action(update_module)
Now I need to write another action as below,
def update_src(modeladmin, request, queryset):
...
form = src_form(request.POST)
if form.is_valid():
one = form.cleaned_data['src']
...
....
admin.site.add_action(update_src)
As we see, the two actions are quite similar. Is there some methods to reuse more code. Maybe decorator should be used?
Upvotes: 0
Views: 1007
Reputation: 553
I haven't tested this, but I think it should work.
def update_func(model):
def update(modeladmin, request, queryset):
...
form = module_form(request.POST)
if form.is_valid():
one = form.cleaned_data[model]
...
...
return update
admin.site.add_action(update_func('module'))
admin.site.add_action(update_func('src'))
Upvotes: 4