In recent years, web applications have become increasingly popular, and many of them require file upload capabilities. In the Django framework, it is not difficult to implement the function of uploading files, but in actual development, we also need to process the uploaded files. Other operations include changing file names, limiting file sizes, and other issues. This article will share some file upload techniques in the Django framework.
1. Configuration file upload items
In the Django project, to configure file upload, you need to configure it in the settings.py file. Below we introduce several important configuration items.
-
File upload path
In settings.py, we can define the path to store uploaded files, as follows:MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
In this configuration item, we define The root directory for storing uploaded files is uploads, and the path of the media file is calculated relative to the directory where the settings.py file is located. We can also add corresponding URL rules in the urls.py of the Django project so that users can get uploaded files by accessing the URL.
-
Supported file formats
File format control is a very important content. We can specify the format of uploaded files through the following configuration items.ALLOWED_FILE_TYPES = ['jpg', 'jpeg', 'png', 'gif', 'pdf']
Note that we must convert all file formats to lowercase letters.
-
File size limit
The Django framework limits the size of all files to no more than 2.5MB by default. If we need to modify this limit value, we can modify it in the settings.py configuration item.MAX_UPLOAD_SIZE = 10485760 # 10MB
In this configuration, we limit the maximum upload file size to 10MB.
2. File upload
We can upload files through Django form components. The following is a simple file upload form example:
<form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="document" accept=".pdf"> <input type="submit" value="Submit"> </form>
Note that the enctype attribute must be multipart/form-data to support file upload.
In the view function, we can use the request.FILES.get() method to get the uploaded file. This method returns a file object. Here is a simple example:
def upload(request): if request.method == 'POST': file = request.FILES.get('document') if file: handle_uploaded_file(file) messages.success(request, '上传成功') return redirect('home') else: messages.error(request, '上传失败') return redirect('upload') else: return render(request, 'upload.html')
In this example, we first get the uploaded file object, and then call the handle_uploaded_file() function to save it to the specified path. In the absence of uploaded files, we can prompt error messages to users through the messages module.
3. File naming
In order to better manage the files uploaded to the server, we recommend naming the uploaded files with a unique file name that contains a timestamp. Here is a simple example:
def handle_uploaded_file(file): date = datetime.now().strftime("%Y%m%d%H%M%S") filename = f"{date}_{file.name}" path = os.path.join(MEDIA_ROOT, filename) with open(path, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk)
First, we use the datetime module to get the current date and time and convert it to string format. We then combine this timestamp with the original filename to generate a new filename. Finally, we combine the new filename with the path to the uploaded file and write the uploaded file contents to the file using the file object's chunks() method.
4. File size
In order to prevent server problems, we need to limit the size of uploaded files. Below is a simple file size check function:
def check_file_size(file): if file.size > MAX_UPLOAD_SIZE: raise ValidationError(f'上传文件大小最大为 {MAX_UPLOAD_SIZE / 1048576} MB')
In this function, we check if the size of the uploaded file exceeds the maximum upload size. If it exceeds, we throw a ValidationError exception and prompt the user. Handle this exception in the view function:
def upload(request): if request.method == 'POST': file = request.FILES.get('document') if file: try: check_file_size(file) except ValidationError as e: messages.error(request, e) return redirect('upload') else: handle_uploaded_file(file) messages.success(request, '上传成功') return redirect('home') else: messages.error(request, '上传失败') return redirect('upload') else: return render(request, 'upload.html')
In this way, we can have better control over the size of the uploaded file.
Summary:
- Implementing file upload in the Django framework requires certain configurations, including defining the file upload path, supported file formats, and limiting file size.
- File upload is implemented through Django form component, and the view function can obtain the uploaded file through the request.FILES.get() method.
- After the file is uploaded, we recommend renaming the file and using the timestamp to generate a unique file name.
- Limit the size of uploaded files.
The above is the detailed content of File upload skills in Django framework. For more information, please follow other related articles on the PHP Chinese website!

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools
