Django 1.11 use template from an app as admin template

193 views Asked by At

as the title said i am having a problem using a template in an admin view
here is my worktree

project
 |-- project/
 |-- myapp/
     |-- templates/
         |-- admin/
             |-- file.html

settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'myapp/templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

ModelAdmin.py

class ModelAdmin(admin.ModelAdmin):
    actions = ['export']

    def export(self,request, queryset):
        paragraphs = ['first paragraph', 'second paragraph', 'third paragraph']
        pdfkit.from_file('file.html', 'out.pdf', paragraphs)
admin.site.register(Model, ModelAdmin)

but i am getting "No such file: file.html" error enter image description here

enter image description here

1

There are 1 answers

2
Alasdair On

pdfkit does not know about your TEMPLATES setting. You need to provide the path relative to your project directory.

pdfkit.from_file('myapp/templates/admin/file.html', 'out.pdf', paragraphs)

However this will treat the file.html as an html file. If it is a Django template that you want to render, you could use render_to_string and from_string.

from django.template.loader import render_to_string
html = render_to_string(request, 'admin/file.html', {...}) 
pdfkit.from_string(html, 'out.pdf')