In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you how to achieve file upload and download Django, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!
1. Preface
File upload and download as basic functions are very common in Web projects. How to achieve file upload and download in Django projects?
two。 Practice: 2-1 enter the virtual environment, create a project and Appworkon django3# create project django-admin startproject file_up_and_down_demo# enter the project root directory cd file_up_and_down_demo/# create an Appdjango-admin startapp index2-2 create template directory and configure settings.py
Create a templates folder under index App, and then configure App and template directories in the project configuration file settings.py
# settings.py# configuration AppINSTALLED_APPS = ['django.contrib.admin',' django.contrib.auth', 'django.contrib.contenttypes',' django.contrib.sessions', 'django.contrib.messages',' django.contrib.staticfiles', 'index',] TEMPLATES = [{' BACKEND': 'django.template.backends.django.DjangoTemplates' 'DIRS': [# configuration template directory os.path.join (BASE_DIR,' index/templates')], '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',],},},] 2-3 create a file model And map to the database
Take the default sqlite as an example, customize a model that represents a file in models.py under index App
The model contains three fields:
File name
File save path
Upload time
# index App models.pyfrom django.db import modelsfrom django.utils import timezone# file model class FileModel (models.Model): # File name name = models.CharField (max_length=50) # File save path path = models.CharField (max_length=100) # upload time upload_time = models.DateTimeField (default=timezone.now)
Then, execute the following two commands under the project root to map the model structure to the database
# Database Mapping Python3 manage.py makemigrationspython3 manage.py migrate2-4 Custom form controls
Create a form file forms.py under index App
Internally customize a form class that inherits from forms.Form
# index App forms.pyfrom django import formsclass FileForm (forms.Form): file = forms.FileField (# supports multi-file upload widget=forms.ClearableFileInput (attrs= {'multiple': True}), select file' for label=',) 2-5 add upload / download routing URL
Add routing URL for upload and download functions
# Project urls.pyfrom django.contrib import adminfrom django.urls import path, includeurlpatterns = [path ('admin/', admin.site.urls), path (', include ('index.urls'))] # index App urls.pyfrom django.urls import pathfrom .views import * urlpatterns = [# upload path (', index_view, name='index'), # download path ('download/', download_view, name='download')] 2-6 write template files
Create a simple template file upload.html in the templates folder of index App
Among them
Form represents the form entity object passed by the view function
Form.as_p stands for rendering all form elements in field format
# index App upload.html Home Page-upload File {% csrf_token%} {{form.as_p}} 2-7 upload View function
Write the view function of upload function in views.py under index App
It is important to note that we need to create a upload folder in the project root directory ahead of time to store the uploaded files
# index App views.pydef index_view (request): "" upload file: param request:: return: "if request.method = 'POST': form = FileForm (request.POST) Request.FILES) if form.is_valid (): # selected file files = request.FILES.getlist ('file') # traversal writes to the database for file in files: # writes to the database file_model = FileModel (name=file.name, path=os.path.join ('. / upload') File.name)) file_model.save () # write to the server local destination = open (os.path.join (". / upload", file.name) 'wb+') for chunk in file.chunks (): destination.write (chunk) destination.close () # indicates that the upload is successful return HttpResponse (' upload successful!') Else: form = FileForm () return render (request, 'upload.html', locals ()) 2-8 download view function
Next, write the view function of the download function
# index App views.pydef download_view (request, id): "" download file: param request:: param id: file id: return: "file_result = FileModel.objects.filter (id=id) # if the file exists Download the file if file_result: file = list (file_result) [0] # File name and path name = file.name path = file.path # read the file file = open (path, 'rb') response = FileResponse (file) # encode the file name using urlquote response [' Content-Disposition'] = 'attachment Filename= 's'% urlquote (name) return response else: return HttpResponse ('file does not exist!') 2-9 run and test
Run the project, access the address below, and upload a file
Open the sqlite database using Pycharm and found that a file record was successfully inserted and the file was uploaded to the upload folder
Then visit the following address to implement the file download function "where file_id represents the id value of the file"
Http://127.0.0.1:8000/download/file_id
The above is all the contents of the article "how to upload and download files in Django". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.