Django上传表单错误:'InMemoryUploadedFile'对象没有属性'COOKIES'

时间:2012-02-16 02:10:31

标签: django-forms django-uploads

您好我是Django的新手我正在尝试构建一个简单的上传应用程序。

forms.py

from django import forms

class Song(forms.Form):
song = forms.ImageField()

models.py

from django.db import models
class Song(models.Model):
song = models.ImageField(upload_to='songs')

views.py

def upload(request):

if request.method  == 'POST':
    form = Song(request.POST, request.FILES)
    if form.is_valid():
        handle_uploaded_file(request.FILES['song'])
        return HttpResponseRedirect('/done/')

else:
    form = Song()
    return render_to_response('upload.html', {
    'form': form},
    context_instance=RequestContext(request)
    )

def handle_uploaded_file(f):
    destination = open('/home/fh/Desktop/netz/media/name.txt', 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()

模板

<form action="/upload/" enctype="multipart/form-data" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>

当我测试它时,我收到此错误。我甚至都不知道这意味着什么。谁能弄清楚我做错了什么?

AttributeError at /upload/

'InMemoryUploadedFile' object has no attribute 'COOKIES'

Request Method:     POST
Request URL:    http://localhost:8080/upload/
Django Version:     1.3.1
Exception Type:     AttributeError
Exception Value:    

'InMemoryUploadedFile' object has no attribute 'COOKIES'

Exception Location:     /usr/local/lib/python2.6/dist-packages/django/middleware  /csrf.py in process_view, line 116
Python Executable:  /usr/bin/python
Python Version:     2.6.6
Python Path:    

['/usr/lib/python2.6',
 '/usr/lib/python2.6/plat-linux2',
 '/usr/lib/python2.6/lib-tk',
 '/usr/lib/python2.6/lib-old',
 '/usr/lib/python2.6/lib-dynload',
 '/usr/local/lib/python2.6/dist-packages',
 '/usr/lib/python2.6/dist-packages',
 '/usr/lib/python2.6/dist-packages/PIL',
 '/usr/lib/python2.6/dist-packages/gst-0.10',
 '/usr/lib/pymodules/python2.6',
 '/usr/lib/pymodules/python2.6/gtk-2.0',
 '/home/fh/Desktop/netz/Klangmagnet',
 '/home/fh/Desktop/netz/Klangmagnet/Klangmagnet']

Server time:    Wed, 15 Feb 2012 19:51:30 -0600

1 个答案:

答案 0 :(得分:0)

检查是否在admin.py中覆盖模型的查询集。像:

def queryset(self, request):
    qs = super(MainClass, self).queryset(request)
    return qs.only( field1, field2,... ) 

然后,请确保在查询集中包含图像字段。像:

def queryset(self, request):
    qs = super(MainClass, self).queryset(request)
    return qs.only( field1, field2,....,ImageFieldName )