Python Django ImageField upload_to 路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34563454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django ImageField upload_to path
提问by user3025403
I'm having trouble understanding and using Django's ImageField.
我在理解和使用 Django 的 ImageField 时遇到问题。
I have a model:
我有一个模型:
class BlogContent(models.Model):
title = models.CharField(max_length=300)
image = models.ImageField(upload_to='static/static_dirs/images/')
description = models.TextField()
My file system is currently:
我的文件系统目前是:
src
|---main_project
|---app_that_contains_blog_content_model
|---static
|---static_dirs
|---images
When I run the server and go to the Admin page, I can add BlogContent objects. After choosing an image for the image field, the image has a temporary name. However, after I save this object I can't find the image in the folder specified by the upload_to path.
当我运行服务器并转到管理页面时,我可以添加 BlogContent 对象。为图像字段选择图像后,图像具有临时名称。但是,保存此对象后,在upload_to 路径指定的文件夹中找不到该图像。
What is the correct way to do this?
这样做的正确方法是什么?
采纳答案by Ivan Semochkin
Your image would be uploaded to media
folder, so it's better change path in model like images/
, and they will be upload to media/images
您的图像将被上传到media
文件夹,因此最好在模型中更改路径,例如images/
,它们将被上传到media/images
In settings.py
add this
在settings.py
添加这个
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
In url.py
在 url.py
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [....
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And then, if you want to display all this image, use something like this
in view.py
BlogContent.objects.all()
然后,如果您想显示所有这些图像,请在 view.py
BlogContent.objects.all()
And render it like this:
并像这样渲染它:
{% for img in your_object %}
<img src="{{ img.image.url }}" >
{% endfor %}
回答by doniyor
static
in upload_to
doesnot make sense, since user-uploaded images go into media/
folder.. you need these:
static
在upload_to
没有意义,因为用户上传的图像进入media/
文件夹..你需要这些:
image = models.ImageField(upload_to='blog/%Y/%m/%d')
and all images land in:
并且所有图像都位于:
media/blog/2016/01/02/img_name.jpg
you access it in template like this:
您可以像这样在模板中访问它:
<img src="{{ blog.image.url }}">
in settings:
在设置中:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')