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