【发布时间】:2016-02-23 19:56:10
【问题描述】:
大家好,我在代码的这一部分有我的问题。我从全局变量上传了多个文件。
file_car = None # Global variable
在我看来.py
if request.method == 'POST':
if file_car is None:
print request.FILES
file_car = [request.FILES.get('dzfile[%d]' % i)
for i in range(0, len(request.FILES))]
我需要这样使用,因为我需要在很多其他视图中使用这些图像。但问题是当我想保存时
for f in file_car:
print f
myfyle= File(f)
#myfyle.open()
aux = Attachment()
aux.name= f
aux.car = car
aux.save() # here is the error. I tried opening the file but it said you cannot reopen the file
它让我对关闭的文件进行 I/O 操作。我对此感到抓狂。对不起我的英语不好
如果有帮助,这里是一个更具压缩性的代码
from django.core.files import File
def createCarView(request):
global file_car
if request.method == 'POST':
if file_car is None:
form = CarForm(request.POST, request.FILES) # other valus
print request.FILES # Print all the file that I get
file_car = [request.FILES.get('dzfile[%d]' % i)
for i in range(0, len(request.FILES))] # Have all the fileS!
if form.is_valid():
# omitted all the other part of the form!
car.save()
for f in file_car:
print f
#myfyle.open()
aux = Attachment()
aux.name=myfyle
aux.car = car
aux.save() #Error in here
print aux.name
file_car=None # cleaning the global var
return HttpResponseRedirect('/car/create')
models.py
class Attachment(models.Model):
car = models.ForeignKey('Car', on_delete=models.CASCADE)
name = models.FileField(_('File'),
upload_to=upload_to_get,
)
【问题讨论】:
-
哪一行出现 I/O 错误?
-
aux.save 给我报错
-
File和Attachment类是什么? -
如果代码更具压缩性,则添加编辑