我将文件名作为实例获取,文件很容易保存到数据库中,没有任何问题。但我需要检查文件扩展名并将文件保存为单独的
我期待这样的输出 单独的文件扩展名并相应保存
phots
image1.jpg
image2.jpg
text
text1.txt
text2.txt
这是我的模特课
class Album(models.Model):
file_upload = models.FileField(upload_to=content_file_name)
name_content = models.CharField(max_length=100)
功能就在这里
def content_file_name(instance, filename):
upload_dir = os.path.join('uploads', 'resource')
return os.path.join(upload_dir, filename)
答案 0 :(得分:0)
使用splitext
获取扩展程序:
def content_file_name(instance, filename):
name, ext = os.path.splitext(filename)
ext = ext.lstrip(".") # Remove leading dot
if ext in ("jpg", "jpeg", "png"):
subdir = "phots"
elif ext in ("txt", "asc"):
subdir = "text"
else:
subdir = extension
upload_dir = os.path.join('uploads', 'resource', subdir)
return os.path.join(upload_dir, filename)
答案 1 :(得分:0)
您可以使用.endswith功能并检查
if filename.endswith("jpg") or silename.endswith("jpeg"):
subdir = "phots"
elif filename.endswith("txt") or filename.endswith("asc"):
subdir = "docs"
答案 2 :(得分:0)
我更喜欢地图而不是if / else语句,因为它更具扩展性。
dir_map = {".jpg" : "photos",
".jpeg" : "photos",
".png" : "photos",
".txt" : "text",
".asc" : "text"
}
_, ext = os.path.splitext(filename)
subdir = dir_map.get(ext, "other")
return os.path.join("uploads", "resource", dir_map.get(ext, "other"), filename)