Search code examples
pythondjangodjango-storage

.pdf is damaged after it has been stored and downloaded


I have stored a .pdf in a models.FileField, and made it downloadable for the users. But when i download the file, it is damaged. Can anyone tell if I'm storing it correctly or point me in some direction? My setup is the following:

models.py

class Barcard(models.Model):
    name = models.CharField(max_length=30)
    drinks = models.ManyToManyField(Drink)
    barcardFile = models.FileField(blank=True, upload_to='barcard') 
    mixingFile = models.FileField(blank=True, upload_to='mixing') 

    def generateFiles(self):
        bashCommand = 'make -C tkweb/apps/drinks/drinkskort/'
        subprocess.call(bashCommand, shell=True)
        barFile = open('tkweb/apps/drinks/drinkskort/bar_drinks.pdf', encoding = "ISO-8859-1")
        mixFile = open('tkweb/apps/drinks/drinkskort/mixing_drinks.pdf', encoding = "ISO-8859-1")
        self.barcardFile.save(self.name+'_barcard',File(barFile))
        self.mixingFile.save(self.name+'_mixing',File(mixFile))

view.py

def barcardGen(request):
    if request.method =='POST':
        card = request.POST.get('barcard')
        card_obj = Barcard.objects.get(id=card)
        barcardName = card_obj.name
        card_obj.generateFiles()
        return HttpResponseRedirect('/drinks/download/'+card)
    else:
        return HttpResponseRedirect('/drinks/')

def download(request, barcard_id):
    if request.method == 'GET':
        barcard = get_object_or_404(Barcard, pk=barcard_id)
        return render(request, 'drinks/download.html', {'barcard':barcard})
    else:
        return HttpResponseRedirect('/drinks/')

template/drinks/download.py

{% extends "drinks/base.html" %}
{% block fulltitle %}Drinks{% endblock %}
{% block content %}
<h1>{{ barcard.name }}</h1>
<p> Download barkort her: <a href='{{barcard.barcardFile.url}}'>{{barcard.name}} barkort</a> </p>
<p> Download blandekort her: <a href='{{barcard.mixingFile.url}}'>{{barcard.name}} blandeliste</a></p>
{% endblock %}

Solution

  • PDF files are binary files. You should read them using binary mode rb not specifying a textual encoding:

    barFile = open('tkweb/apps/drinks/drinkskort/bar_drinks.pdf', "rb")
    mixFile = open('tkweb/apps/drinks/drinkskort/mixing_drinks.pdf', "rb")