Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
927 views
in Technique[技术] by (71.8m points)

python - Django ImageField upload_to path

I'm having trouble understanding and using Django's 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.

What is the correct way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your image would be uploaded to the media folder, so it's better to change path in the model like images/, and they will be upload to media/images

In settings.py add this

MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

In 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()

And render it like this:

{% for img in your_object %}
    <img src="{{ img.image.url }}" >
{% endfor %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...