All articles, tagged with “django”

HTML to PDF in Django

I’ve been involved in a number of project where I need to create pdf reports from a set of data using the Django framework. The easiest way for me to do this is generate the pdf directly from html.

I will provide a list of software required, and how to program a django view to generate the pdf.

Here’s the software you’ll need:

pisa: http://pypi.python.org/pypi/pisa/

ReportLab: http://www.reportlab.org/downloads.html

html5lib: http://code.google.com/p/html5lib/downloads/list

Here’s a simple view to generate the pdf.

#view.py

import cStringIO as StringIO
import ho.pisa as pisa
from django.http import HttpResponse
from django.template.loader import render_to_string

def my_view(request, *args, **kwargs):

    html = render_to_string('some_template.html', RequestContext(request, {
        'title': 'This is a test PDF document'
    }))
    result = StringIO.StringIO()
    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
    response = HttpResponse(result.getvalue(), mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=document.pdf'
    return response

Enjoy

Dynamically change field attributes in a Django ModelForm

I’ve encountered situations using Django’s ModelForm where I’ve needed the form to validate differently then the default behavior in various instances. Here’s an example of how I changed all the fields from the default of not being required to all being required without much effort:

class AddressRequiredForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(AddressForm, self).__init__(*args, **kwargs)
        for name, field in self.fields.iteritems():
            if name not in ['address2',]:
                field.required = True

    class Meta:
        model = Address

This is pretty simple, but it saved me a lot of time by not having to re-type each field name with a new set of properties.