Dojcument'对象不可下标访问 Django

2 投票
1 回答
6592 浏览
提问于 2025-04-18 08:57

我在上传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

请帮我解决这个问题。

1 个回答

1

你的问题出在这里:

path = os.path.join(settings.MEDIA_ROOT, newdoc)

^ newdoc 是一个模型实例,你不想把模型本身放在路径里 - 你想要的是上传文件的路径,所以应该这样:

path = os.path.join(settings.MEDIA_ROOT, newdoc.docfile)

撰写回答