如何在上传文件后列出文件?我想显示它们,以便以后查看和下载。
这是我的代码。
models.py
class UploadFile(models.Model):
file = models.FileField(upload_to='files/%Y/%m/%d')
forms.py
class UploadFileForm(forms.ModelForm): pass
class Meta:
model = UploadFile
views.py
@login_required(login_url='/accounts/login/')
def home(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
new_file = UploadFile(file = request.FILES['file'])
new_file.save()
return HttpResponseRedirect(reverse('main:home'))
else:
form = UploadFileForm()
data = {'form': form}
return render_to_response('upload.html', data,
context_instance=RequestContext(request))
答案 0 :(得分:0)
无需从表单中恢复文件并保存 - 只需使用您的模型保存即可。视图必须是这样的:
@login_required(login_url='/accounts/login/')
def home(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
form.save() # saving model instance
return HttpResponseRedirect(reverse('main:home'))
else:
form = UploadFileForm()
data = {'form': form}
return render_to_response('upload.html', data, context_instance=RequestContext(request))
之后,您可以从模型中获取所有上传的文件:
files = [upload_file.file for upload_file in UploadFile.objects.all()]
并将其显示给用户