Django ImageField upload_to路径 [英] Django ImageField upload_to path
问题描述
我无法理解和使用Django的ImageField。
I'm having trouble understanding and using Django's ImageField.
我有一个模型:
class BlogContent(models.Model):
title = models.CharField(max_length=300)
image = models.ImageField(upload_to='static/static_dirs/images/')
description = models.TextField()
我的文件系统目前是:
src
|---main_project
|---app_that_contains_blog_content_model
|---static
|---static_dirs
|---images
当我运行服务器并转到Admin页面,我可以添加BlogContent对象。为图像字段选择图像后,图像具有临时名称。但是,在保存此对象之后,我找不到upload_to路径指定的文件夹中的图像。
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.
正确的方法是什么?
推荐答案
您的图像将被上传到媒体
文件夹,所以更好的改变模型中的路径,如 images /
,他们将被上传到媒体/图片
Your image would be upload to media
folder, so beter change path in model like images/
, and they will be upload to media/images
在 settings.py
中添加
MEDIA_URL ='/ media /'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
在 url.py
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [....
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
然后,如果要显示所有此图像,请使用这样的
在 view.py
BlogContent.objects.all()
And then, if you want to display all this image, use something like this
in view.py
BlogContent.objects.all()
并呈现如下:
{% for img in your_object %}
<img src="{{ img.image.url }}" >
{% endfor %}
这篇关于Django ImageField upload_to路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!