Media files in jsonresponse

Hello i m tring to use json response with media uploated by the user and I am having some difficulties. Right now my folders look like this.

  • main
  • app
    • templates
    • static
      • js
      • img

This is the only way where I can type the url of an image and found it. I tried to use a media file outside the app, inside the app and netheir work. And is strange because when I upload or delete a model that includes an image the view can find it easily regarlees the location of the file.

In my models i have the following

class categoria(models.Model):
     imagen  = models.ImageField(upload_to='img/', default = None,blank=True)
    def serialize(self):
        imagen_url = None
        if self.imagen: 
            imagen_url = self.imagen.url 
        return {
            "id": self.id,
            "imagen": imagen_url,
        }

My view

def obtener_categorias(request):
    categorias = categoria.objects.filter()
    return JsonResponse([categoria.serialize() for categoria in categorias], safe=False)

What i want to do with my js file

function categorias(){
    const selecion = document.querySelector('#seleccion');
    selecion.innerHTML = "";
    fetch(`/obtener_categorias`)
    .then(response => response.json())
    .then(categorias => {
        categorias.forEach(categoria => {
            const element = document.createElement('div');
            const imagen = document.createElement('img');
            imagen.src = categoria.imagen;
            element.innerHTML +=   `<img src="${categoria.imagen}" width="100" height="100"> `
            selecion.appendChild(imagen);
            selecion.appendChild(element);
        });
    })
}

The only way the template show the img (if i do the same in the js file it works too):

<img src="static/{{ categoria.imagen }}" width="100" height="100">

My settings

STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / 'static_files'

MEDIA_URL = 'media/'
MEDIA_ROOT = BASE_DIR / 'media_files'

How can i resolve this in a way it works and also doesnt difficult things in the deployment

Please clarify what it is that your view is returning.

(Specifically, show the JSON that the obtener_categorias view is returning for a sample case.)

Note, uploaded media files should be stored separately from your static files and not part of the same directory structure. It should be a completely different directory. Based on the settings shown here, you should have a media_files directory at the same level as main and app.

The view is giving the serialize() version of the model categoria. Example

[{"id": 5, "imagen": "/media/imagenes/categoria/00.jpg"}, {"id": 6,"imagen": "/media/imagenes/categoria/11.png"}]

And yes I tried to save the images in the media folders (in the level as you said) separately from the static but when I try to use the url in a js file or a template I get 404 errors

Please show the actual location of the 00.jpg file in your directory structure.

Nevermind I solved adding the following in mu url.py

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
else:
    urlpatterns += staticfiles_urlpatterns()