Login

Custom 'save' method, automate creating pdf file from entry.

Author:
I159
Posted:
September 28, 2011
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

Save method, useful for automate pdf files creation if you want to use the file in database.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import os.path
from reportlab.pdfgen import canvas

from django.db import models
from django.conf import settings


class Entry(models.Model):
    doc = models.TextField()
    file = models.FilePathField(
            path=os.path.join(settings.MEDIA_URL, '/files'), match='*\.pdf',)
    
    def save(self, *args, **kwargs):
        """Writing entry content to new pdf file, saving it in file system
        and make record to database."""
        
        counter = 0
        
        def make_path(counter):
            """Check existing and make new file."""
            
            path = os.path.join(
            settings.STATICFILES_DIRS[1], 'files', 'f' + str(counter) + '.pdf')
            
            if os.path.isfile(path):
                counter += 1
                return make_path(counter)
            return path
            
        curr_path = make_path(counter)
        
        pdf_file = canvas.Canvas(curr_path)
        pdf_file.drawString(100, 750, self.doc)
        pdf_file.save()
        self.file = curr_path
        super(Entry, self).save(*args, **kwargs)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.