Home > Article > Backend Development > Introduction to Django Admin's implementation of uploaded image verification function
Django offers many features for future developers: a mature standard library, an active user community, and all the benefits of the Python language. While other web frameworks claim to offer the same thing, Django is unique in that it has a built-in administrative application - admin.
admin provides advanced Create-Read-Update-Delete (CRUD) functionality out of the box, reducing the time required to rework work. This is key to many web applications, as programmers can quickly browse their database models while developing; non-technical end users can use the admin to add and edit site content during deployment.
There is an ImageField field in my models, which is used to save user avatars. I hope to verify the size of the avatar when uploading through Django Admin. If it is too large, an error will be reported and it will not be saved.
There are many methods on the Internet, some are implemented through third-party software, and some are verified by writing forms yourself. I think it is too complicated, and the requirements are not high. I just want the simplest method.
The following method is to verify the image size by overwriting the save_model() of admin.ModelAdmin. If the image is larger than 20K, an error will be reported and not saved:
from django.contrib import messages class YourModeAdmin(admin.ModelAdmin): ... def save_model(self, request, obj, form, change): #不保存大图片 if obj.picture and obj.picture.size > 20480: messages.set_level(request, messages.ERROR) messages.error(request, 'The picture\'s too large. It\'s supposed smaller than 20K.') else: obj.save()
Finally, show the implemented Django website. Thanks to andrew liu for his online tutorial:
The above content introduces Django Admin to implement uploaded image verification function. Relevant knowledge, I hope it will be helpful to everyone!
For more related articles about Django Admin’s implementation of uploaded image verification function, please pay attention to the PHP Chinese website!