Django implementation file (image) after uploading automatically modify the name and page upload pictures when the various reminders:
1, first add a folder in your project, such as: System to add __init__.py and storage.py files under the folder, and add the following code in the storage.py:
#-*-coding:utf-8-*- fromDjango.core.files.storageImportFilesystemstorage fromDjango.httpImportHttpResponseclassimagestorage (filesystemstorage): fromDjango.confImportSettingsdef __init__(Self,location=settings. Media_root, Base_url=settings. Media_url):#InitializeSuper (Imagestorage,self).__init__(Location,base_url)def_save (self,name,content):#re-file upload ImportOs,time,hashlib#get file suffixext = os.path.splitext (name) [1] #file directoryD =os.path.dirname (name)#Define folder namefn = HASHLIB.MD5 (Time.strftime ('%y%m%d%h%m%s'). Encode ('Utf-8') . Hexdigest () name= Os.path.join (d,fn+ext)#calling the parent class method returnSuper (Imagestorage,self) _save (name,content)
2. Add the following code to the models.py file:
fromDjango.dbImportModels fromDatetimeImportdatetime fromSystem.stroageImportImagestorage#Create your models here.#Article Inquiry Formclassarticle (models. Model): Title= Models. Charfield (max_length=250, Null=false, verbose_name='title', unique=True) Content= Models. TextField (verbose_name='content') Add_time= Models. Datetimefield (verbose_name='Add Time', default=DateTime.Now) Update_time= Models. Datetimefield (verbose_name='Modification Time', null=True) State= Models. Integerfield (verbose_name='Status', Default=1) cat_id= Models. ForeignKey (Category, on_delete=models. CASCADE) T=DateTime.Now () Cover_map= Models. ImageField (verbose_name='Indent Graph', upload_to='article/%y/%m/%d', default='1.png', storage=imagestorage ())classMeta:verbose_name='article'Ordering= ['-add_time'] def __str__(self):returnSelf.titledefDelete (self, using=none, keep_parents=False):Print(1111)
Django uploads images simple validation and automatically modifies image names