Creating a Django admin action to duplicate a record

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

Here is a usage example.

The administrator clicks the checkbox next to the entry in the application that they want to duplicate. Admin chooses Duplicate from the admin action drop-down menu. Admin clicks. Django admin creates a duplicate entry with a new identifier. The page is updated, and a new duplicate is added with an identifier. The administrator clicks on the new duplicate entry and edits it. Admin clicks on save.

Am I crazy or is this a pretty direct action for the administrator?

I use these documents for reference: http://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/

I think something like this:

In my application:

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

I know what's wrong ... but am I close to that?

+3
source share
2 answers

You have the right idea, but you need to iterate through a set of queries and 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"
+8
source

Perhaps this work is 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()
0
source

Source: https://habr.com/ru/post/1770767/


All Articles