I have a model Document, and the admin can upload an image to a FileField. When a document/image is successfully uploaded, I also save a sha256 "fingerprint" of the image to test if an admin tries to upload a duplicate image. If a duplicate image is detected, I don't save the duplicate image and display an error message to the admin through the messages framework. However, I also get the message that the document was successfully uploaded. How can I prevent this from happening?
My code in an abbreviated form:
class Document(Model):
document_id = models.AutoField(primary_key=True)
computed_sha256 = models.CharField(editable=False, max_length=64, default="foobar")
storage_file_name = models.FileField('File name', upload_to=settings.DOCUMENT_FOLDER_ORIGINALS, default=settings.DEFAULT_IMAGE_XXXLARGE_PATH,)
class DocumentAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if form.is_valid():
if not change:
# Uploading one or more images
files = request.FILES.getlist('storage_file_name')
if files:
for f in files:
# Check if this file has been uploaded before by checking the fingerprint
_file = form.cleaned_data["storage_file_name"]
sha256 = image_processing_utils.compute_sha256(_file)
duplicate_files = Document.objects.filter(computed_sha256 = sha256)
if len(duplicate_files) > 0:
messages.add_message(request, messages.WARNING, 'Uploading a duplicate of "%s" and it will not be saved' % f.name)
break;
# more image processing stuff
else:
# some more image processing stuff
obj.metadata = form.cleaned_data['metadata']
super().save_model(request, obj, form, change)
The resulting admin page with the two messages when I try to upload a duplicate image:
I am not sure where Django is adding the positive message that the image was uploaded correctly. How do I go about removing it and just displaying the message that the duplicate image was not uploaded?
Thanks!
Mark