In Django, files are usually not stored directly into a MySQL database, but are stored in a file system or cloud storage, where only the path or metadata of the files is stored.
1. Create Django projects and applications
If there are no projects and applications, create one first:
django-admin startproject myproject cd myproject python startapp myapp
2. Configure MySQL database
existConfigure MySQL database connections:
DATABASES = { 'default': { 'ENGINE': '', 'NAME': 'mydatabase', # Database name 'USER': 'root', # Database username 'PASSWORD': 'password',# Database Password 'HOST': 'localhost', # Database Host 'PORT': '3306', # Database Port } }
Make sure the MySQL client library is installed:
pip install mysqlclient
3. Create a model
existmyapp/
Create a model to store file information:
from import models class UploadedFile(): name = (max_length=255, verbose_name="File Name") file = (upload_to='uploads/', verbose_name="document") uploaded_at = (auto_now_add=True, verbose_name="Upload time") def __str__(self): return class Meta: verbose_name = "Upload file" verbose_name_plural = "Upload file"
4. Create a form
existmyapp/
Create a form to handle file uploads:
from django import forms from .models import UploadedFile class UploadFileForm(): class Meta: model = UploadedFile fields = ['name', 'file']
5. Create a view
existmyapp/
Create views in to handle upload, preview and download of files:
from import render, get_object_or_404 from import HttpResponse from .models import UploadedFile from .forms import UploadFileForm import os def upload_file(request): if == 'POST': form = UploadFileForm(, ) if form.is_valid(): () return render(request, 'upload_success.html') else: form = UploadFileForm() return render(request, '', {'form': form}) def preview_file(request, file_id): file = get_object_or_404(UploadedFile, id=file_id) return render(request, '', {'file': file}) def download_file(request, file_id): file = get_object_or_404(UploadedFile, id=file_id) response = HttpResponse(, content_type='application/force-download') response['Content-Disposition'] = f'attachment; filename={()}' return response
6. Configure URL
existmyapp/
Configure URL routing in:
from import path from . import views urlpatterns = [ path('upload/', views.upload_file, name='upload_file'), path('preview/<int:file_id>/', views.preview_file, name='preview_file'), path('download/<int:file_id>/', views.download_file, name='download_file'), ]
existmyproject/
The URL of the application is included:
from import admin from import path, include urlpatterns = [ path('admin/', ), path('myapp/', include('')), ]
7. Configure media files
existConfigure the storage path of the media file:
MEDIA_URL = '/media/' MEDIA_ROOT = (BASE_DIR, 'media')
existmyproject/
Add the URL configuration for the media file:
from import settings from import static urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
8. Create a template
existmyapp/templates/
Create the following template file in the directory:
(File upload page)
<!DOCTYPE html> <html> <head> <title>Upload File</title> </head> <body> <h1>Upload File</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> </body> </html>
upload_success.html
(Uploaded successfully page)
<!DOCTYPE html> <html> <head> <title>Upload Success</title> </head> <body> <h1>File Uploaded Successfully</h1> <a href="{% url 'upload_file' %}" rel="external nofollow" >Upload another file</a> </body> </html>
(File Preview Page)
<!DOCTYPE html> <html> <head> <title>Preview File</title> </head> <body> <h1>{{ }}</h1> <p>Uploaded at: {{ file.uploaded_at }}</p> <a href="{% url 'download_file' %}" rel="external nofollow" >Download</a> </body> </html>
9. Configure SimpleUI
existInstall and configure SimpleUI in:
INSTALLED_APPS = [ ... 'simpleui', 'myapp', ... ]
SimpleUI will automatically beautify the Django backend interface, you canFurther configure the themes and other options for SimpleUI in the SimpleUI.
10. Run the server and test it
Run the Django development server:
python runserver
accesshttp://127.0.0.1:8000/myapp/upload/
Test files upload, preview and download.
11. Deployment
In a production environment, make sure to configure how static files and media files are processed and consider using cloud storage services such as AWS S3 to store uploaded files.
Summarize
Through the above steps, the administrator can upload files and store file information in the MySQL database, and support front-end preview and download functions. SimpleUI is used to beautify the Django backend interface and improve the user experience.
This is the article about Django+simpleui implementing file upload and preview function. For more related Django simpleui file upload and preview content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!