我最好如何循环这样的表单(表单中还有其他代码,但这是图像上传的示例)
<form action="{% url "upload" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="image_file">
<input type="file" name="image_file2">
<input type="file" name="image_file3">
<input type="file" name="image_file4">
<input type="file" name="image_file5">
<input type="submit" value="submit" />
</form>
适用于单个文件上传,但需要多文件上传:
def image_upload(request):
if request.method == "POST" and request.FILES["image_file"]:
image_file = request.FILES["image_file"]
fs = FileSystemStorage()
filename = fs.save(image_file.name, image_file)
image_url = fs.url(filename)
print(image_url)
return render(request, "upload.html", {
"image_url": image_url
})
return render(request, "upload.html")
只是不知道如何循环它,以便图像与文件名一起存储在数据库的 var 中(稍后)也只是一个想法,可能并不总是上传所有五个文件,可能是三个或没有
如果我理解正确的话,您只是想循环遍历 5 个字段(image_file 到 image_file5),并保存每个字段(如果上传了文件)?
如果是这样,那几乎非常简单,因为您可以使用计算结果或变量,而不仅仅是硬编码字符串。 唯一(轻微)的问题是第一个字段没有用“1”命名,但是可以使用 if 条件轻松处理。 为了便于理解,我将保持简单;如果我要创建此功能,我可能会采取完全不同的方法。 无论如何,使用 for 循环,循环范围 1 到 5(range 函数返回一个从第一个参数到第二个参数减 1 的迭代器,这就是为什么我们使用 range(1, 6) 而不是 Range(1 , 5)),并使用当前迭代器编号构造当前文件字段的名称。 像这样:
def image_upload(request):
if request.method == "POST":
image_urls = dict()
for i in range(1, 6):
file_key = f"image_file{i}" if i > 1 else "image_file" # If you're using Python 2, f-strings won't work, but you could do either "image_file{}".format(i) or "image_file%d" % (i, )
image_file = request.FILES.get(file_key, None) # This format retrieves the file if the named file exists, otherwise it will result in None (because I specified None as the default falue in the second argument). This is safer against potential errors, if the field doesn't exist or has no file associated
if image_file: # Since we stored the image file, or None if missing, in the variable called image_file, we'll just check that; if it has a non-Non value, this line resolves to True
fs = FileSystemStorage()
filename = fs.save(image_file.name, image_file)
image_urls[file_key] = fs.url(filename)
else:
image_urls[file_key] = "" # Or maybe you'd want None here
#
# Here I am rendering the template after saving all 5 files, and including the URLs for all 5. But I don't know what the intent
# is here, so you might need to write something else. In the context for this render call, I am unpoacking the dictionary key/value
# pairs recorded in the loop, into keyword variable pairs.
return render(request, "upload.html", {
**image_urls,
})
return render(request, "upload.html")
我知道这个回复晚了两年,但我在寻找东西时遇到了这个,我不敢相信它还没有解决。