上传excel文件并保存该文件时出现此错误。
我的model.py文件
class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')
在视图中我将该文件保存到特定位置 views.py文件是
def excel(request):
print "you in main"
if request.method == 'POST':
print "you in post"
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
path = os.path.join(settings.MEDIA_ROOT, newdoc)
print path
print "you in"
newdoc.save()
wb = xlrd.open_workbook(path)
sh = wb.sheet_by_index(0)
c = 1
while c < len(sh.col(0)):
first = sh.col_values(0)[c]
second = sh.col_values(1)[c]
c=c+1
return HttpResponseRedirect(reverse('upload.views.excel'))
else:
form = UploadFileForm() # A empty, unbound form
documents = Document.objects.all()
return render_to_response('property/list.html',{'documents': documents, 'form': form},context_instance=RequestContext(request))
我的html文件是
<!-- List of uploaded documents -->
{% if documents %}
<ul>
{% for document in documents %}
<li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
<!-- Upload form. Note enctype attribute! -->
<form action="/property/excel/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
我得到的错误是
TypeError at /property/excel/
'Document' object is not subscriptable
Request Method: POST
Request URL: http://127.0.0.1:8000/property/excel/
Django Version: 1.5
Exception Type: TypeError
Exception Value:
'Document' object is not subscriptable
Exception Location: C:\Python27\lib\ntpath.py in splitdrive, line 125
请帮我解决这个问题
答案 0 :(得分:0)
你的问题在这里:
path = os.path.join(settings.MEDIA_ROOT, newdoc)
^ newdoc
是一个模型实例,您不希望模型本身成为路径的一部分 - 您希望在那里上传文件路径,因此:
path = os.path.join(settings.MEDIA_ROOT, newdoc.docfile)