这对我帮助很大,我使用了@ShravaN 的解决方案并将其扩展为也将图像保存在相关的内联模型中。我认为代码不是最好的,但它可以工作。如果您有任何改进的想法,请做!
def save_model(self, request, obj, form, change):
# Django always sends this when "Save as new is clicked"
if '_saveasnew' in request.POST:
# Get the ID from the admin URL
original_pk = request.resolver_match.kwargs['object_id']
# Get the original object
original_obj = obj._meta.concrete_model.objects.get(id=original_pk)
# Iterate through all it's properties
self._copy_image_fields(obj, original_obj)
obj.save()
def _copy_image_fields(self, obj, original_obj):
for prop, value in vars(original_obj).items():
# if the property is an Image
# (don't forget to import ImageFieldFile!)
if isinstance(getattr(original_obj, prop), ImageFieldFile):
setattr(obj, prop, getattr(original_obj, prop)) # Copy it!
def save_related(self, request, form, formsets, change):
if '_saveasnew' in request.POST:
# Get the ID from the admin URL
original_pk = request.resolver_match.kwargs['object_id']
# Get the original object
original_obj = form.instance._meta.concrete_model.objects.get(
id=original_pk
)
form.save_m2m()
for formset in formsets:
instances = formset.save(commit=False)
if instances:
related = list(filter(lambda r: r.related_model == formset.model, original_obj._meta.related_objects))
related = related[0] if related else None
# related: ManyToOneRel
if related:
field_name = f"{related.name}_set" if not related.related_name else related.related_name
related_set = getattr(original_obj, field_name)
else:
# TODO: warning?
continue
for ori, ni in zip(related_set.all(), instances):
# instance: Model
# we need to figure out which field is in the original
# object
self._copy_image_fields(ni, ori)
ni.save()
formset.save_m2m()
else:
super(LiveEventAdmin, self).save_related(request, form, formsets, change)