In the Django admin interface, is there a way to duplicate an element?

Just wondering if there is an easy way to add functionality to duplicate an existing list in the admin interface?

When entering data, we were faced with a situation where many elements exchange common data with another element, and to save time it would be very nice to quickly duplicate the existing list and change only the changed data. Using a better model structure would be one way to reduce data duplication, but there may be a situation where duplicate data needs to be changed on an individual basis in the future.

+59
python django django-models django-admin
07 Oct '08 at 23:23
source share
3 answers

You can save as by simply adding this to your ModelAdmin:

save_as = True 

This replaces the Save and Add More button with the Save As button. β€œSave as” means that the object will be saved as a new object (with a new identifier), and not the old object.

+97
Oct 07 '08 at 23:26
source share

There is a better (but not built-in) solution here:

https://github.com/RealGeeks/django-modelclone

From their README:

Django Admin has a save_as function that adds a new button to the change page to save a new instance of this object.

I don’t like how this function works, because you will keep an identical copy of the original object (if you do not get verification errors), as soon as you click this link, and if you forget to make small changes, you will get a duplicate of the existing one in the new object object.

On the other hand, django-modelclone offers an intermediate view that basically pre-populates the form for you. This way you can change and then save a new instance. Or just walk away without side effects.

+4
Apr 10 '18 at 11:10
source share

You can also apply this method: stack overflow

In my case, with a unique constraint in the 'name' field, this action works and can be requested from any form:




 def duplicate_jorn(modeladmin, request, queryset): post_url = request.META['HTTP_REFERER'] for object in queryset: object.id = None object.name = object.name+'-b' object.save() return HttpResponseRedirect(post_url) 



0
Jun 12 '19 at 16:04 on
source share



All Articles