Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ImageField upload_to path

Tags:

python

django

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?

like image 517
user3025403 Avatar asked Jan 02 '16 06:01

user3025403


2 Answers

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 %}
like image 59
Ivan Semochkin Avatar answered Oct 06 '22 01:10

Ivan Semochkin


static in upload_to doesnot make sense, since user-uploaded images go into media/ folder.. you need these:

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')
like image 35
doniyor Avatar answered Oct 06 '22 00:10

doniyor