8

I want to create a Django Admin Action that allows me to create a duplicate of a record.

Heres the use case.

Admin clicks the checkbox next to a record in an app that they want to duplicate. Admin selects "Duplicate" from the admin action drop down menu. Admin clicks go. Django admin creates a duplicate record with a new id. Page is refrshed and new duplicate is added with id. Admin clicks on the new, duplicated record, and edits it. Admin clicks save.

Am I crazy or is this a pretty straight forward Admin Action?

I've been using these docs for reference: http://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/

I'm thinking something like this:

In my app:

def duplicate(modeladmin, request, queryset):
    new = obj.id
    queryset.create(new)
    return None
duplicate.short_description = "Duplicate selected record"

I know that's not right... but is my thinking close?

Dave Merwin
  • 1,382
  • 2
  • 22
  • 44
  • 2
    it's not an action, but you can get a 'save as' link in the edit form this way: http://stackoverflow.com/questions/180809/in-the-django-admin-interface-is-there-a-way-to-duplicate-an-item – Thomas Schreiber Oct 21 '10 at 16:54

2 Answers2

18

You have the right idea but you need to iterate through the queryset then duplicate each object.

def duplicate_event(modeladmin, request, queryset):
    for object in queryset:
        object.id = None
        object.save()
duplicate_event.short_description = "Duplicate selected record"
Jeff Triplett
  • 2,216
  • 1
  • 16
  • 8
  • 2
    Now the trick is, how to also duplicate any FK models that point to this model. – Dave Merwin Oct 29 '10 at 18:02
  • 2
    Remember to also add the duplicate action to the actions list in the MyappAdmin class for your application Myapp: actions = [duplicate_event] – tatlar Dec 21 '12 at 22:07
  • To copy FK and M2M read [link](http://blogs.law.harvard.edu/rprasad/2012/08/24/using-django-admin-to-copy-an-object/) – Miguel Febres Jan 09 '13 at 15:09
  • Is possible do it compatible with mptt ?? – carlituxman Aug 08 '13 at 21:56
  • 1
    This approach will not copy relations, using save_as is a way better approach that copies model including relations: http://stackoverflow.com/questions/180809/in-the-django-admin-interface-is-there-a-way-to-duplicate-an-item – ribozz Sep 02 '14 at 16:13
0

Maybe this work to for you.

def duplicate_query_sets(queryset, **kwargs):
    for p in queryset:
        p.pk = None
        for i, v in kwargs.iteritems():
            setattr(p, i, v)

        p.save()
Pjl
  • 1,752
  • 18
  • 21