Загрузить сгенерированный PDF в Django Model - PullRequest
0 голосов
/ 17 мая 2019

В настоящее время я создаю веб-приложение, в котором я сгенерировал pdf-файл данных из моделей Django с библиотекой reportlab и загрузил его как HttpResponse (content_type = 'application / pdf'), и он работает правильно.Теперь он возвращается из вида. Я хочу загрузить его в модель Django, а не загружать его.Возможно ли, пожалуйста, помочь мне, это о моем последнем проекте года?Я буду очень благодарен вам.

В настоящее время я использую последнее обновление Django и библиотеку reportlab для генерации pdf.

Ниже приведена функция, которая генерирует pdf и извлекает его как HttpResponse.

def format1(personal_info,education,skills,experience,statement,languages,user):
    education_list = list()
    skills_list = list()
    experience_list = list()
    for i in education:
        temp_dict = dict()
        temp_dict["degree"] = i.Degree
        temp_dict["institute"] = i.Institute
        temp_dict["city"] = i.City
        temp_dict["grade"] = i.Grade 
        education_list.append(temp_dict)
    for i in skills:
        temp_dict = dict()
        temp_dict["skill"] = i.Skill_Title
        temp_dict["level"] = i.Level 
        temp_dict["description"] = i.Description 
        skills_list.append(temp_dict)
    for i in experience:
        temp_dict = dict()
        temp_dict["job"] = i.Job_Title
        temp_dict["organization"] = i.Organization
        temp_dict["city"] = i.City
        temp_dict["timeperiod"] = i.TimePeriod 
        experience_list.append(temp_dict)
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment;filename=' + user + ".pdf"    
    c = canvas.Canvas(response, pagesize=letter)
    width,height = letter
    # profile information
    c.setFont("Helvetica-Bold",22)
    c.drawString(0.5*inch,height-0.7*inch,personal_info[0].FullName)
    c.setFont("Helvetica",12)
    c.drawString(0.5*inch,height-0.9*inch,personal_info[0].PermanentAddress)
    c.drawString(0.5*inch,height-1.1*inch,personal_info[0].Email)
    c.drawString(0.5*inch,height-1.3*inch,personal_info[0].Phone)
    # horizontal line
    c.line(0.5*inch,height-1.5*inch,width-0.5*inch,height-1.5*inch)
    # education section
    c.setFont("Helvetica-Bold",18)
    c.drawString(0.5*inch,height-2*inch,"Education")
    count = 2.0
    for i in education_list:
        c.setFont("Helvetica-Bold",12)
        c.drawString( (width-0.5*inch)/2,height-(count)*inch, i['degree'] )
        c.setFont("Helvetica",12)
        c.drawString( (width-0.5*inch)/2,height-(count+0.2)*inch, i['institute'] + ", " + i['city'] )
        c.drawString( (width-0.5*inch)/2,height-(count+0.4)*inch, i['grade'] )
        count = count + 0.7
    # horizontal line
    c.line(0.5*inch,height-(count+0.2)*inch,width-0.5*inch,height-(count+0.2)*inch)
    count = count + 0.7
    # skills section
    c.setFont("Helvetica-Bold",18)
    c.drawString(0.5*inch,height-count*inch,"Skills")
    c.setFont("Helvetica",12)
    index = math.ceil(len(skills_list)/2)
    for i in range(math.ceil(len(skills_list)/2)):
        try:
            c.drawString( (width-0.5*inch)/2,height-(count)*inch,skills_list[i]['skill'])
            c.drawString( ((width-0.5*inch)/2) + inch*2,height-(count)*inch,skills_list[index]['skill'])
            index = index + 1
        except:
            c.drawString( (width-0.5*inch)/2,height-(count)*inch,skills_list[i]['skill'])
        count = count + 0.2
    # horizontal line
    c.line(0.5*inch,height-(count+0.2)*inch,width-0.5*inch,height-(count+0.2)*inch)
    count = count + 0.7
    # experience section
    c.setFont("Helvetica-Bold",18)
    c.drawString(0.5*inch,height-count*inch,"Work Experience")
    for i in experience_list:
        c.setFont("Helvetica-Bold",12)
        c.drawString( (width-0.5*inch)/2,height-(count)*inch, i['job'] )
        c.setFont("Helvetica",12)
        c.drawString( (width-0.5*inch)/2,height-(count+0.2)*inch, i['organization'] + ", " + i['city'] )
        c.drawString( (width-0.5*inch)/2,height-(count+0.4)*inch, i['timeperiod'] )
        count = count + 0.7
    # horizontal line
    c.line(0.5*inch,height-(count+0.2)*inch,width-0.5*inch,height-(count+0.2)*inch)
    # ----------------------------------------
    c.showPage()
    c.save()
    return response

Ниже моя модель Django, в которой я хочу загрузить сгенерированный pdf

class Application(models.Model):
    job = models.ForeignKey(Posts,on_delete=models.CASCADE)
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    status = models.BooleanField(default=False,blank=False)
    cv = models.FileField(upload_to="pdf-files")
    def __str__(self):
        return self.job.organization.Name

Ниже приведен код, в котором я пытаюсь загрузить сгенерированный pdf в модель

response = format1(person,education,skills,experience,statement,langs,username)
        file = ContentFile(response.content)
        print(file) # output = Raw Content
        obj = models.Application(user=user,job=job,cv=file)
        obj.save() 

Я хочу загрузить сгенерированный pdf-файл в эту модель, но результаты - это пустое поле в этой модели после выполнения этого кода.

...