Internet Public ip address and django static file

2019-07-27 11:33发布

问题:

I used django and weasyprint to make an application which print a pdf file with picture and css file which design my pdf file. I used nginx, gunicorn and supervisor to deploy my application. In my intranet all is ok. When i used INTERNET PUBLIC IP ADDRESS to publish it on internet, my pdf file don't show anymore picture and css design. but all the application's static files work well I see my gunicorn log but nothing. I use Nginx to serve my static file. this the configuration

upstream app_server { server unix:/webapps/myapp/run/gunicorn.sock fail_timeout=0; }

server {

listen 80;

server_name 127.0.0.1;

client_max_body_size 4G;

access_log /webapps/myapp/logs/nginx-access.log;

error_log /webapps/myapp/logs/nginx-error.log;

location /static/ { alias /webapps/myapp/basegenecirdes/public/static/; }

location /media/ { alias /webapps/myapp/media/; }

location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off;

   if (!-f $request_filename) {
       proxy_pass http://app_server;
       break;
   }

}

in my views.py to call a pdf file, i use this

html = render_to_string('pdf/print.html', {'pagesize':'A4'}) response = HttpResponse(content_type="application/pdf",) response['Content-Disposition'] = 'inline; filename="print.pdf"' weasyprint.HTML(string=html,base_url=request.build_absolute_uri()).write_pdf(response)
return response

static image file:

<img style="background-color: white" src="{% static "image/photo_50x48.png" %}">

media image file

<img alt="{{ a.nom }}" src="{{ a.photo.thumbnail.url }}" >

is somebody have the same problem?

回答1:

After reading your edits, this question appears to be a duplicate of PDF output using Weasyprint not showing images (Django)

You have the first part of the answer already in your code. But I don't see this part in your write_pdf() call:

For the HTML styles to show on the PDF, add presentational_hints=True as per the Weasyprint docs:

pdf = html.write_pdf(stylesheets=[CSS(settings.STATIC_ROOT + '/css/detail_pdf_gen.css')], presentational_hints=True);