Introduction to Django Admin's implementation of uploaded image verification function

高洛峰
Release: 2017-03-07 16:02:50
Original
1691 people have browsed it

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()
Copy after login

Finally, show the implemented Django website. Thanks to andrew liu for his online tutorial:

Django Admin实现上传图片校验功能介绍

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!