我需要一些帮助来了解如何将文件从我的 django 站点下载到用户机器上。我已经创建了一个相当基本的上传文件的方法。这些文件是一个类的实例,并保存在我的“媒体”文件夹中。我需要帮助的是如何提供文件。我希望用户能够访问一个页面并单击他们想要下载的文件。出于某种原因,我找不到有关如何执行此操作的任何资源。这是我此时的文件
网址.py
url(r'^admin/', include(admin.site.urls)),
url(r'^upload/', views.upload),
url(r'^download/', views.download),
url(r'^success/', views.success),
)
if settings.DEBUG:
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
) + urlpatterns
模型.py
class WorkSheet(models.Model):
worksheet_name = models.CharField(max_length= 150, default = '')
creator = models.ForeignKey(User, default = True)
worksheet_file = models.FileField(upload_to = 'worksheets', default = True)
number_of_stars = models.PositiveIntegerField(default = 0)
category = models.CharField(max_length = 100, default = '')
class UploadWorkSheetForm(ModelForm):
class Meta:
model = WorkSheet
exclude = ('number_of_stars',
'creator',)
视图.py
def upload(request):
if request.method == 'POST':
form = UploadWorkSheetForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return http.HttpResponseRedirect('/success/')
else:
form = UploadWorkSheetForm()
return render(request, 'upload.html', {'form': form})
def download(request):
return render_to_response('download.html')
def success(request):
return render_to_response('upload_success.html')
所以基本上我希望用户访问 www.mysite.com/download 并能够下载文件。谢谢!!
. . . . . . . . .
另外,我的上传文件视图没有这样的处理程序是否有问题?
def handle_uploaded_file(file,path=''):
filename = file._get_name()
destination_file = open('%s/%s' % (settings.MEDIA_ROOT, str(path) + str(filename)), 'wb+')
for chunk in file.chunks():
destination_file.write(chunk)
destination_file.close()