Django ImageField upload_to path

I'm having trouble understanding and using 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 currently:

 src |---main_project |---app_that_contains_blog_content_model |---static |---static_dirs |---images 

When I start the server and go to the admin page, I can add BlogContent objects. After selecting an image for the image field, the image has a temporary name. However, after saving this object, I cannot find the image in the folder specified in the upload_to path.

What is the right way to do this?

+6
source share
3 answers

Your image will be uploaded to the media folder, so it’s better to change the path in the model, for example images/ , and they will be uploaded 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 do it like this:

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

static in upload_to does not make sense, since the images uploaded by the user get into the 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 the template as follows:

 <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') 
+6
source

You should use a media path, not a static one. See docs

+1
source

Source: https://habr.com/ru/post/1239899/


All Articles