我正在尝试存储从django表单上传的文件。我在报告表单中上传文件,我想将文件存储在我的服务器上,以便以后可以访问它们。
我的模特:
class Report(models.Model):
author = models.ForeignKey(User, null=True)
date = models.DateTimeField(auto_now_add=True)
description = models.CharField(max_length=128)
content = models.TextField()
security = models.BooleanField(default=False)
我的表格:
class ReportForm(forms.ModelForm):
description = forms.CharField(max_length=128)
content = forms.TextInput()
security = forms.BooleanField(required=False, initial=False, label="Private")
files = forms.FileField(required=False)
class Meta:
model = Report
fields = ('description','content','security','files',)
我的观点:
def index(request):
report_list=Report.objects.all()
report_form=ReportForm(request.POST, request.FILES)
if report_form.is_valid():
report = report_form.save()
report.author = request.user
report.save()
for count, x in enumerate(request.FILES.getlist("files")):
with open(settings.MEDIA_ROOT, 'wb+') as destination:
for chunk in x.chunks():
destination.write(chunk)
context_dict = {'Reports' : report_list, 'Report_Form' : report_form}
return render(request, 'index.html', context_dict)
我的HTML:
<form id="report_form", method="post",action="/myapplication/",enctype="multipart/form-data">
<h3>New Report:</h3>
{% csrf_token %}
<label for="id_description">Description:</label>
<input class="form-control" id="id_description" maxlength="128" name="description" type="text"/>
<label for="id_content">Content:</label>
<input class="form-control" id="id_content" maxlength="2000" name="content" type="text"/>
<label for="id_files">Files:</label>
<input type="file" name="files" multiple>
<label for="id_security">Security:</label>
Public <input type="radio" id="id_security" name="security" value="False" checked>
Private <input type="radio" id="id_security" name="security" value="True">
<br>
<input class="btn btn-default" type="submit" name="Submit" value="Submit"/>
</form>
为什么我无法在request.FILES中找到上传的文件?