大家好我在代码的这一部分有我的问题。我从o全局变量上传了多个文件。
file_car = None # Global variable
和我的views.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,
)
答案 0 :(得分:0)
代码不清楚,但错误说你应该打开文件,那么尝试这样的事情怎么样? :
for f in file_car:
with open(f,"a") as f:
print f
myfyle= File(f)
aux = Attachment()
aux.name=myfyle
aux.car = car
aux.save()