开发者

Create a Django Admin Action to Duplicate a Record

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?


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"


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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜