Home > Mobile >  Django renders the HTML file without including static files(CSS styles, images)
Django renders the HTML file without including static files(CSS styles, images)

Time:04-23

There I have tried to render the HTML file

    html_message = get_template('mail.html').render(context=data)
    email = EmailMultiAlternatives(
        "Subject",
        html_message,
        settings.EMAIL_HOST_USER,
        ['[email protected]', ],
    )
    email.attach_alternative(html_message, 'text/html')
    email.send(fail_silently=False)

The HTML file

    {% load static %}
    <!doctype html>
    <html lang="en">
      <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Title</title>
      <link rel="stylesheet" href="{% static 'mail.css' %}">
    </head>
    <body>
      <header>
        <div>
          <img  src="{% static 'logo.svg' %}" alt="">
        </div>
      </header>
    </body>

As the Result HTML file was rendered without static files.
When I'm rendering the HTML like a view, everything works great

CodePudding user response:

The issue is that the generated part using static uses relative urls for static assets (such as /static/logo.svg). I think that's the expected behaviour, and since the URL is not absolute (the hostname part is missing), there is no way an email client will be able to get it correctly.

That also explains why it works on the online version.

You might find a good lead here: Django Get absolute url for static files

Edit: more precisely, the static tag generates the asset path using the STATIC_URL setting, which people tend to default to static/. One way to solve your issue would be then to set an absolute base url here instead (ie. https://your-hostname.com/static/)

  • Related