Search code examples
djangoangularnginxdjango-staticfiles

django angular load static files - image in assets folder get 404


i have a assets/image folder in angular src folder and i left all of my images there, i have many component and child component that are using that images like <img src"../../../assets/image/test.png">,

i build my angular app and place all files to static folder , in nginx i point it to load from static folder and in django in template i used index.html to load the static files like below: now my app will run but no file that have address like "../../../file" in angular load all get 404 like this :

http://hello.com/bird.65c8b9bce67b6a965a9c.png (error 404)

if i put a static keyword front of address it like http://hello.com/static/bird.65c8b9bce67b6a965a9c.png image will load .. how can i handle this issue?

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title> site </title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="{% static 'favicon.png' %}">
<link rel="stylesheet" href="{% static 'styles.921a613cd46f44e0d5a0.css' %}"></head>
<body>
  <app-root>Loading .  .  .</app-root>
<script type="text/javascript" src="{% static 'runtime.6afe30102d8fe7337431.js' %}"></script>
<script type="text/javascript" src="{% static 'polyfills.b0205464c9bd4e7fe3b3.js' %}"></script>
<script type="text/javascript" src="{% static 'scripts.59ed76cc23ba77b0ec72.js' %}"></script>
<script type="text/javascript" src="{% static 'main.08947dd689f13d4027ea.js' %}"></script>
</body>
</html>

also i aleady added

urlpatterns += static(base.STATIC_URL, document_root=base.STATIC_ROOT) + \
               static(base.MEDIA_URL, document_root=base.MEDIA_ROOT)

to end of my urls.py and i run python manage.py collectstatic

nginx server:

server {
    listen 80;
    server_name hello.com;
    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/vertical/academy;
    }

    location / {
        include proxy_params;
       #proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://unix:/home/vertical/academy/academy.sock;
    }
}

Solution

  • Your problem is that Angular is pointing the resources to Django's root.

    You need to specify resourcesOutputPath parameter to ng bulid command:

    ng build --output-path /path-to-django-app/static --resources-output-path static
    

    So it will point to http://hello.com/static/bird.65c8b9bce67b6a965a9c.png intead of http://hello.com/bird.65c8b9bce67b6a965a9c.png

    Note that resources output path is relative to output path.

    See the Options section here: https://angular.io/cli/build