在Django中存储生产中的私有文档可以通过以下步骤实现:
from django.db import models
class PrivateDocument(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
file = models.FileField(upload_to='private_documents/')
created_at = models.DateTimeField(auto_now_add=True)
MEDIA_ROOT = os.path.join(BASE_DIR, 'private_documents')
MEDIA_URL = '/media/'
from django.shortcuts import render, redirect
from django.core.files.storage import FileSystemStorage
def upload_private_document(request):
if request.method == 'POST' and request.FILES['file']:
file = request.FILES['file']
fs = FileSystemStorage()
filename = fs.save(file.name, file)
PrivateDocument.objects.create(owner=request.user, file=filename)
return redirect('private_document_list')
return render(request, 'upload_private_document.html')
def private_document_list(request):
documents = PrivateDocument.objects.filter(owner=request.user)
return render(request, 'private_document_list.html', {'documents': documents})
from django.urls import path
from . import views
urlpatterns = [
path('upload/', views.upload_private_document, name='upload_private_document'),
path('list/', views.private_document_list, name='private_document_list'),
]
<!-- private_document_list.html -->
{% for document in documents %}
<p>{{ document.file.name }}</p>
<a href="{{ document.file.url }}">Download</a>
{% endfor %}
这样,你就可以在Django中存储生产中的私有文档了。请注意,以上示例中的代码仅供参考,具体实现可能需要根据你的项目需求进行调整。
领取专属 10元无门槛券
手把手带您无忧上云