django static files not served to HTML-EMail template
Asked Answered
S

2

5

I am running Django on a local Vagrant arch machine on a Win7 host. I set up my environment variables from Django in a .env file. In my app all static files are served correctly and everything works as it should.

Problem: I am not able to serve my static files (images) in my html-email templates. Until now i served them as hardcoded filer URL's and i want to change that.

I am passing BASE_URL BASE_URL=http://127.0.0.1:8001, which is proved working, as context to the template and loading static as usual:

{% load static %} 

and calling it in HTML tag:

<img src="{{BASE_URL}}{% static 'img/my_image.png' %}">

In the received email the URL of the image is http://127.0.0.1:8001/static/img/my_image.png which looks right but triggers a 404.

What am i missing??

(Please dont ask me if the image is in the corresponding folder, it is ;)

Skull answered 5/4, 2017 at 7:41 Comment(2)
Your website is running on a local VM, but your email is being send to 'the outside'. Outside of your VM that local 127.0.0.1 url is useless.Cultured
it would be better to have a hostname and set the hostname map to 127.0.0.1 from your /etc/hosts fileVershen
V
7

As already said by @dentemm: Your email service provider try to fetch images from http://127.0.0.1:8001/static/img/my_image.png but he cannot while address of your server is visible only from your local computer. Therefore images are not found. One way to solve this is to render template and take screenshot of template and send that in email body(to see if it renders properly) E.g. here.

Another way is to upload img files to some publicly accessible server.

Vandyke answered 5/4, 2017 at 7:54 Comment(2)
Thanks guys, so obvious. I thought because its opened in my browser on my machine it still can reach the localhost.Skull
your link to #2193299 does not workLacasse
I
0

A great solution that works and is faster is to pass the server url as context when rendering the html template. You can get that from django.contrib.sites.shortcuts.

Example

from django.contrib.sites.shortcuts import get_current_site

site = get_current_site(request)
message = render_to_string(template, {
    "domain": site.domain,
})
Interpol answered 7/1 at 18:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.