0

There are some files in a directory, and I want to return url of every file in the directory. How can i do that in django ?

dir_id_1
-->img1.png
-->img2.png
-->img3.png
dir_id_2
-->img4.png

When user send a get request to correspond endpoint with the directory name, It should return urls of images. Something like this.

[10.10.10.10:8000/.../dir_id_1/img1.png, 10.10.10.10:8000/.../dir_id_1/img2.png, 10.10.10.10:8000/.../dir_id_1/img2.png]

PS: I am keeping these images in filesystem, not in db.

erondem
  • 482
  • 1
  • 11
  • 24
  • its good to ask where you're stuck while solving the problem not the solution of the problem itself. Try yourself and if you're facing any particular problem then update the same question. – Vishal Singh Jul 17 '20 at 07:32

2 Answers2

0

You can read the whole files and directories in which you store the images using syntax like this, then you can map the entries and edit them using the URL pattern for images

import os
entries = os.listdir('[directory_name]/')
Luthfi
  • 274
  • 4
  • 12
0

if you keep images in some directory located on your server you can get them by their path in your domain

from django.contrib.sites.models import Site
from os import listdir
from os.path import isfile

path_name = "your/dir/path/name"

def get_urls_in_dir(pathname):
    hostname = Site.objects.get_current().domain
    file_urls = []
    for file in listdir(path_name):
        file_urls.append(hostname + "/" + pathname + "/" + file)
    return file_urls

You will get something like

[
    'example.com/dir_id_1/img1.png',
    'example.com/dir_id_1/img2.png',
    'example.com/dir_id_1/img3.png',
]

But it is not good approach

If you use Django it is better to use ImageField() with MEDIA_URL, which will keep images on directory you will specify in MEDIA_URL, and only store image path in your database. By adopting this method you can just get required image by

image_object.url

Here is good example of configuring MEDIA_URL