No. 387, django+xadmin build on-line standard online education platform-site upload resources configuration and display
First look at static static files and upload the difference between the resources, staticstatic files inside the general prevention of our website-style files, including CCS,JS, site-style pictures
Upload a resource is a user action uploaded pictures and other resources
Upload a resource's configuration
1, first create a folder named Media in the project to save the user upload
2,settings.py file configuration The path of the upload resource
# Upload resource path, if picture, upload file, etc. ' /media/ ' # set the upload resource prefix name ' Media ') # set the upload file path
After this configuration, when the user uploads the file, according to the Data table class upload field settings, the file upload,Media folder, as follows
Data table Classes
classcourseorg (models. Model): Name= Models. Charfield (max_length=50, verbose_name='Name of Institution') desc= Models. TextField (verbose_name='Organization Description') Category= Models. Charfield (max_length=20, verbose_name='type of organization', default='PXJG', choices= ('PXJG','Training Institutions'), ('GX','University'), ('GR','Personal')) Click= Models. Integerfield (default=0, verbose_name='Number of clicks') Fav_nums= Models. Integerfield (default=0, verbose_name='Number of Favorites') Image = models. ImageField (upload_to='org/%y/%m', verbose_name=' cover map ' , max_length=100 ) address= Models. Charfield (max_length=150, verbose_name='Agency Address') City= Models. ForeignKey (Citydict, verbose_name='foreign key City table') Add_time= Models. Datetimefield (Default=datetime.now, verbose_name='Add Date') classMeta:verbose_name='Course Organization Table'verbose_name_plural=Verbose_namedef __str__(self):returnSelf.name
You can now see the upload file installation date to save the file, then how to set the filename
Set the upload file name
1, first add a folder in your project, such as: system
Add and file under the folder __init__.py
storage.py
, and storage.py
add the following code:
#-*-coding:utf-8-*- fromDjango.core.files.storageImportFilesystemstorage fromDjango.httpImportHttpResponse
classimagestorage (filesystemstorage): fromDjango.confImportSettingsdef __init__(Self, location=settings. Media_root, Base_url=settings. Media_url):#InitializeSuper (Imagestorage, self).__init__(location, Base_url)#overriding the _save method def_save (self, Name, content):#Name to upload file names ImportOS, time, Random#file name extensionext = os.path.splitext (name) [1] #file directoryD =os.path.dirname (name)#define the file name, month and day, and minute random numberfn = Time.strftime ('%y%m%d%h%m%s') FN= fn +'_%d'% Random.randint (0,100) #rewrite the composition file nameName = Os.path.join (d, Fn +ext)#calling the parent class method returnSuper (Imagestorage, self). _save (name, content)
2. models.py
Add the following code to the file:
Import the classes we set in the database file
Set the storage=imagestorage () execution class in the Upload field, which is storage.py
the class in our custom
from Import imagestoragepic=models. ImageField (upload_to='img/%y/%m/%d',storage=imagestorage ()) # If you upload a file, you can change the ImageField to Filefield
Upload file display
Uploaded files, to be displayed in the foreground or background, you need to configure to display
To configure a dedicated URL route map for upload file access
fromDjango.conf.urlsImportURL, include#Import Django-free include logic fromDjango.contribImportAdmin fromDjango.views.genericImportTemplateview#Import the Templateview logic that comes with Django from django.views.static import serve # Import the Django-brought serve static resource logic ImportXadmin#Import Xadmin fromApp_users.viewsImportDeng_lu, Zhu_ce, Active_code, Logout#Import Login Logic processing class fromApp_organization.viewsImportOrg_list#Import the Teaching organization logicFrom mxonline.settings import media_rooturlpatterns=[url (r'^xadmin/', xadmin.site.urls), url (r'^index.html', Templateview.as_view (template_name='index.html'), Name='Index'), #RegisterURL (r'^register.html', Zhu_ce.as_view (), name='Register'), url (r'^captcha/', Include ('Captcha.urls'), Name='Captcha'), url (r'^active/(? p<active_de>.*)/$', Active_code.as_view (), name="user_active"), #LoginURL (r'^login.html', Templateview.as_view (template_name='login.html'), Name='Login'), url (r'^deng_lu', Deng_lu.as_view (), name='Deng_lu'), url (r'^logout', Logout.as_view (), name='Deng_lu'), #Teaching InstitutionsURL (r'^org_list.html', Org_list.as_view (), name='org_list'), #dedicated to static resource request mapping, i.e. request mapping in Media upload folder URL (r'media/(? p<path>.*) $', serve, {'document_root' : Media_root}) # Media_root The PATH variable for the configuration upload file ]
You can now display pictures in the background
The foreground display can be displayed by stitching the path through the settings.py configured upload resource prefix name.
HTML file
<a href="org-detail-homepage.html"> " $"height=" -" class="scrollloading"Data-url=" {{media_url}}{{ji.image}} "/> {#need to splice static resource path #}</a>
NOTE: If the HTML file is to get to the media_url of the settings.py configuration, you need to set up a static resource processing class in the configuration file
TEMPLATES = [ { 'Backend':'django.template.backends.django.DjangoTemplates', 'DIRS': [Os.path.join (Base_dir,'Templates')],#Configure the template file path, which is the HTML path 'App_dirs': True,'OPTIONS': { 'context_processors': [ 'Django.template.context_processors.debug', 'django.template.context_processors.request', 'Django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', # Configure HTML page to receive Take Media_url path ], }, },]
No. 387, django+xadmin build on-line standard online education platform-site upload resources configuration and display