簡體   English   中英

如何將 CSS 文件鏈接到 Django 的 pdf.html 文件,修復 FileNotFoundError

[英]How to link CSS file to pdf.html file for Django, fixing a FileNotFoundError

我的 PDF.html 沒有鏈接到任何 CSS 文件,我嘗試了以下方法:

模板PDF.HTML

{% load static %}

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<link href='{% static "css/bootstrap.min.css" %}' rel="stylesheet">
<!-- Material Design Bootstrap -->
<link href='{% static "css/mdb.min.css" %}' rel="stylesheet">
<!-- Your custom styles (optional) -->
<link href='{% static "css/style.min.css" %}' rel="stylesheet">

我對其他模板使用與 base.html 相同的 CSS 文件,它工作正常並鏈接到它們,但對於這個特定的 HTML,它沒有鏈接,所以我試圖找到這個問題的原因

這是base.html

{% load static %}

<!DOCTYPE html>
<html lang="en">

<head>
-----------------------------------------------------

<link href='{% static "css/bootstrap.min.css" %}' rel="stylesheet">
<!-- Material Design Bootstrap -->
<link href='{% static "css/mdb.min.css" %}' rel="stylesheet">
<!-- Your custom styles (optional) -->
<link href='{% static "css/style.min.css" %}' rel="stylesheet">

我正在使用 weazyprint 來獲取 pdf,所以這里是我嘗試使用它的視圖,但它FileNotFoundError at /admin/order/50/pdf/ [Errno 2] No such file or directory: 'C:\\\\Users\\\\User\\\\Desktop\\\\static_rootcss/pdf.css'返回FileNotFoundError at /admin/order/50/pdf/ [Errno 2] No such file or directory: 'C:\\\\Users\\\\User\\\\Desktop\\\\static_rootcss/pdf.css'

@staff_member_required
def admin_order_pdf(request, order_id):
    order = get_object_or_404(Order,ordered=True, id=order_id)
    html = render_to_string('pdf.html', {'order': order})
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = f'filename="order_{order.id}.pdf"'    
    weasyprint.HTML(string=html).write_pdf(response, 
                    stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')])
    return response

我在settings.py中使用followig配置

# Static files (CSS, JavaScript, Images)

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')]
VENV_PATH = os.path.dirname(BASE_DIR)
STATIC_ROOT = os.path.join(VENV_PATH, 'static_root')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

嘗試:

weasyprint.HTML(string=html).write_pdf(response, 
                    stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + '/css/pdf.css')])

編輯

似乎settings.STATIC_ROOT沒有指向正確的路徑。 因此,添加正確的路徑即STATICFILES_DIRS將起作用。 所以:

@staff_member_required
def admin_order_pdf(request, order_id):
    order = get_object_or_404(Order,ordered=True, id=order_id)
    html = render_to_string('pdf.html', {'order': order})
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = f'filename="order_{order.id}.pdf"'    
    weasyprint.HTML(string=html).write_pdf(response, 
                    stylesheets=[weasyprint.CSS(settings.STATICFILES_DIRS[0]+ '/css/pdf.css')])
    return response

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM