Categories
Python Answers

How to render HTML to PDF in a Python Django site?

To render HTML to PDF in a Python Django site, we can create our own function.

For instance, we write

import cStringIO as StringIO
from xhtml2pdf import pisa
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from cgi import escape


def render_to_pdf(template_src, context_dict):
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = StringIO.StringIO()

    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))

to define the render_to_pdf function that uses the pisa.pisaDocument constructor to create the PDF from the html string.

We get html from render the template with the context to a HTML string.

Then we create a new HttpResponse that returns the PDF file as the response.

We set the content_type to application/pdf.

And we render result.getvalue to return the PDF.

Then in our view, we add

def myview(request):
    return render_to_pdf(
            'mytemplate.html',
            {
                'pagesize':'A4',
                'mylist': results,
            }
        )

to render the mytemplate.html template into a PDF and return it as the response with render_to_pdf.

And then in mytemplate.html, we write

<!DOCTYPE HTML>
<html>
    <head>
        <title>My Title</title>
        <style type="text/css">
            @page {
                size: {{ pagesize }};
                margin: 1cm;
                @frame footer {
                    -pdf-frame-content: footerContent;
                    bottom: 0cm;
                    margin-left: 9cm;
                    margin-right: 9cm;
                    height: 1cm;
                }
            }
        </style>
    </head>
    <body>
        <div>
            {% for item in mylist %}
                RENDER MY CONTENT
            {% endfor %}
        </div>
        <div id="footerContent">
            {%block page_foot%}
                Page <pdf:pagenumber>
            {%endblock%}
        </div>
    </body>
</html>
Categories
Python Answers

How to get the protocol + host name from URL with Python?

To get the protocol + host name from URL with Python, we can use the urlparse function.

For instance, we write

from urllib.parse import urlparse

parsed_uri = urlparse('http://example.com/questions/1234567/blah-blah-blah-blah' )
result = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
print(result)

to call urlparse with a URL.

And then we get the protocol with uri.scheme.

And the host name is stored in the uri.netloc property.

Categories
Python Answers

How to import csv data into Python Django models?

To import csv data into Python Django models, we can call csv.reader.

For instance, we write

with open(path) as f:
        reader = csv.reader(f)
        for row in reader:
            _, created = Teacher.objects.get_or_create(
                first_name=row[0],
                last_name=row[1],
                middle_name=row[2],
                )

to open the file at path with open.

Then we call csv.reader with file f.

And then we loop through the rows and call the get_or_create method to create items that don’t exist in the database from the rows.

Categories
Python Answers

How to get the full or absolute URL (with domain) in Python Django?

To get the full or absolute URL (with domain) in Python Django, we can use the build_absolute_uri method.

For instance, we write

request.build_absolute_uri(reverse('view_name', args=(obj.pk, )))

to call request.build_absolute_uri with reverse('view_name', args=(obj.pk, ) to get the path of the view with reverse.

Then we call “request.build_absolute_uri` with the view path to return the full URL of the view.

Categories
Python Answers

How to render a template variable as HTML with Python Django?

To render a template variable as HTML with Python Django, we can use autoescape off or safe.

For instance, we write

{{ myhtml |safe }}

to use the safe filter to render myhtml as HTML.

Or we use

{% autoescape off %}
    {{ myhtml }}
{% endautoescape %}

to use the autoescape off to render myhtml as HTML.