[英]can we create directory in view? django
I want to create / remove directories in static folder using django's view. 我想使用django的视图在静态文件夹中创建/删除目录。 Is it possible?
可能吗?
Something like, when I run django's view I want to create some extra folders in static folder...then do some processing inside the folder, and remove them later 像这样,当我运行django的视图时,我想在静态文件夹中创建一些额外的文件夹...然后在该文件夹中进行一些处理,然后将其删除
You can create/remove directories from a Django view using os and/or shutil . 您可以使用os和/或shutil从Django视图创建/删除目录。
Your views.py will go something like this - 您的views.py将会像这样-
import os, shutil, errno
from django.conf import settings
def my_view(request):
#Getting static folder path from project settings
static_dir = settings.STATICFILES_DIRS[0]
#Creating a folder in static directory
new_dir_path = os.path.join(static_dir, "new_dir")
try:
os.makedir(new_dir_path)
except OSError as e:
if e.errno != errno.EEXIST:
#directory already exists
pass
else:
print(e)
#Removing a directory
try:
shutil.rmtree(new_dir_path)
except OSError, e:
print(e)
#do the things you want
Note: os.rmdir(path)
can also delete a directory but only if it is empty. 注意:
os.rmdir(path)
也可以删除目录,但os.rmdir(path)
是该目录为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.