How to modify messages displayed in Admin change page?

9 views
Skip to first unread message

Mark Phillips

unread,
Apr 17, 2020, 3:18:16 PM4/17/20
to django users
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 attached image shows the problem.

Where can I find the message that the document was saved properly and remove it from the messages list?

Thanks!

Mark

Screenshot from 2020-04-17 11-49-48.png
Reply all
Reply to author
Forward
0 new messages