3

I'm trying to save a pdf file which is rendered using HTML to a model field right now, it throws this error.

coercing to Unicode: need string or buffer, instance found

this is the code

def save_to_pdf(template_src, context_dict, pk):
    import ipdb; ipdb.set_trace()
    instance = get_object_or_404(
        Project.objects.filter(pk=pk, is_deleted=False))
    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,link_callback=fetch_resources)
    pdfnew=file(pdf)
    instance.structural_info.save('structure.pdf',pdfnew)
    return True

structural_info is the file field. What is the correct way to do it?

Arun Laxman
  • 376
  • 2
  • 15
  • Potential duplicate: https://stackoverflow.com/questions/7514964/django-how-to-create-a-file-and-save-it-to-a-models-filefield – SaeX Apr 23 '23 at 07:18

1 Answers1

7

If you look at the API Documentation documentation:

Note that the content argument should be an instance of django.core.files.File, not Python’s built-in file object. You can construct a File from an existing Python file object like this

from django.core.files import File
# Open an existing file using Python's built-in open()
f = open('/path/to/hello.world')
myfile = File(f)

so if pdf is a string you could use:

from django.core.files.base import ContentFile
myfile = ContentFile(pdf)
instance.structural_info.save('structure.pdf', myfile)
Herbert Poul
  • 4,512
  • 2
  • 31
  • 48