gpt4 book ai didi

python - Django中如何获取上传文件的名称

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:29 25 4
gpt4 key购买 nike

我已经看到了一些关于它的问题,但这些无法解决我的问题,这就是为什么我要问一个新问题。所以,请不要将其标记为重复!

使用Python(3.6)和Django(1.10)我试图获取上传文件的名称,但它返回

AttributeError: 'NoneType' object has no attribute 'name'

这是我尝试过的:来自models.py

sourceFile = models.FileField(upload_to='archives/', name='sourceFile', blank=True)

来自 HTML 模板:

<div class="form-group" hidden id="zipCode">
<label class="control-label" style="font-size: 1.5rem; color: black;">Select File</label>
<input id="sourceFile" name="sourceFile" type="file" class="file" multiple
data-allowed-file-extensions='["zip"]'>
<small id="fileHelp" class="form-text control-label" style="color:black; font-size: .9rem;">
Upload a Tar or Zip
archive which include Dockerfile, otherwise your deployment will fail.
</small>
</div>

来自views.py:

if form.is_valid():
func_obj = form
func_obj.sourceFile = form.cleaned_data['sourceFile']
func_obj.save()
print(func_obj.sourceFile.name)

这里出了什么问题?

请帮帮我!

提前致谢!

最佳答案

要获取文件名,您只需使用 request.FILES 字典(我假设只有 1 个文件正在上传)

示例:

try:
print(next(iter(request.FILES))) # this will print the name of the file
except StopIteration:
print("No file was uploaded!")

请注意,这要求文件作为表单的一部分通过 POST 方法发送。

要将其名称更改为随机字符串,我建议使用 uuid.uuid4,因为这会生成一个随机字符串,该字符串不太可能与已有的任何内容发生冲突。此外,您需要通过提供生成名称的函数来编辑 sourceFile 模型的 upload_to= 部分:

# In models.py

def content_file_name(instance, filename):
filename = "{}.zip".format(str(uuid.uuid4().hex))
return os.path.join('archives', filename)

# later....

sourceFile = models.FileField(upload_to=content_file_name, name='sourceFile', blank=True)

希望这有帮助!

关于python - Django中如何获取上传文件的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47605818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com