django admin action

Posted Almost 6 years ago. Visible to the public. Draft.

Sample duplicate event

This example makes use of clearing the id field (primary key) and then saves the record to produce a duplicate of the record. The user can select as many records from the admin panel and it will duplicate each in the selected query set.

# admin.py
from django.contrib import admin
import django.contrib.admin.options as admin_opt

def dup_event(modeladmin:admin_opt.ModelAdmin, request, queryset):
    for object in queryset:
        from_id = object.id
        object.id = None
        object.save()
        message="dup from {} to {}".format(from_id, object.id)
        modeladmin.log_addition(request=request,object=object,message=message)

dup_event.short_description = "Duplicate Records"

class MyObjAdmin(admin.ModelAdmin):
    list_display = ('id', 'name')
    list_filter = ('name',)
    search_fields = ('name',)
    ordering = ['id']
    actions = [duplicate_event]


admin.site.register(MyObj, MyObjAdmin)

Reference

Cuauhtemoc
Last edit
Almost 6 years ago
Cuauhtemoc
Posted by Cuauhtemoc to Python Django (2018-07-22 14:50)