django框架中用户上传文件的存放位置
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
在urls.py文件中进行路由配置
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
配置完成!
图片上传到指定的文件夹下,防止重名
我们可以在models.py中自己定义一个生成文件名的函数
def custom_upload_path(instance, filename):
class_name = instance.__class__.__name__.lower()
filename = filename.split('.')[0] + str(uuid.uuid4()) + "." + filename.split('.')[-1]
date_str = "%s%s%s" % (datetime.now().year, datetime.now().month, datetime.now().day)
return "{}/{}/{}".format(class_name + "s", date_str, filename)
在模型类中直接调用函数即可
img = models.ImageField(upload_to=custom_upload_path, null=True, blank=True, verbose_name='图片')