0

Can I store PDFs in Django Models.py under ImageField? Documentation doesn't seem to mention PDFs much. I'm thinking of trying something along the lines of:

from django.db import models

class Model(models.Model):
    text = models.CharField(max_length=30, unique=False)
    pdf = models.ImageField(upload_to='media/pdfs')

with a form.py structured like this:

from django import forms
from model.models import Model

class textForm(forms.ModelForm):
    class Meta:
        model = Model
        fields = ('text',)

With a Views.py structured like this:

def user_view(request):
    text = form.cleaned_data.get('text')
    can.drawString(10, 100, Model.text)

    existing_pdf = PdfFileReader(open("media/01.pdf", "rb"))
    page = existing_pdf.getPage(0)
    page.mergePage(new_pdf.getPage(0))
    PdfFileWriter().addPage(page)

    return render(request, "app/fill_form.html", context)
Display name
  • 753
  • 10
  • 28

1 Answers1

2

Try the models.FileField https://docs.djangoproject.com/en/3.0/topics/http/file-uploads/

Here is a snippet from the docs

from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import ModelFormWithFileField

def upload_file(request):
    if request.method == 'POST':
        form = ModelFormWithFileField(request.POST, request.FILES)
        if form.is_valid():
            # file is saved
            form.save()
            return HttpResponseRedirect('/success/url/')
    else:
        form = ModelFormWithFileField()
    return render(request, 'upload.html', {'form': form})

If you need to access uploaded files from the view, they will be in

requests.FILES 

To return a pdf as a view you can follow this post How to show a PDF file in a Django view?

def pdf_view(request):
    with open('/path/to/my/file.pdf', 'r') as pdf:
        response = HttpResponse(pdf.read(), mimetype='application/pdf')
        response['Content-Disposition'] = 'inline;filename=some_file.pdf'
        return response
    pdf.closed

If you have pdf in your models you could just add a editPDF function on your model that can add the selected text the way you're doing (assuming that is working) and save the pdf.

sin tribu
  • 1,148
  • 1
  • 6
  • 14
  • Thank you for the speed of your answer, it took me a while to fully get through the material you shared. I am curious, could you elaborate further on the editPDF function in the model that you mentioned at the end? I have never seen an example of something like that. – Display name Apr 13 '20 at 00:46