查询文件字段如何与外键相关

时间:2017-09-03 23:34:00

标签: python django models

大家好我没有尝试所有我可以查询外键中的文件但它不起作用django抛出一个错误我一直试图这样做很久我现在只是给了,现在我回到它需要帮助!

    from __future__ import unicode_literals

from django.db import models


class Examination(models.Model):
    examination_name = models.CharField(max_length=50, unique=True)

    class Meta:
        verbose_name='examination'
        verbose_name_plural='examinations' 

    def __unicode__(self):
        return self.examination_name

class YearAndExaminationName(models.Model):
    exam_name = models.ForeignKey(Examination)
    examination_year = models.CharField(max_length=4)


    class Meta:
        verbose_name='year and examination name'
        verbose_name_plural='year and examination names'

    def __unicode__(self):
        return self.examination_year


class PastQuestion(models.Model):
    year_and_exam_name = models.ForeignKey(YearAndExaminationName)
    file_name = models.CharField(max_length=40, default='self')
    file = models.FileField(upload_to='uploads/', max_length=100,)
    posted_by = models.CharField(max_length=40)


    def __unicode__(self):
        return self.file_name

我打算通过id或pk从视图中引用来获取pdf来显示文件,但是当我搜索stackoverflow或google时,我得到的是如何将html转换为pdf。

我的观点

def jamb_detail(request):
    instance = get_object_or_404()
    context = {
    "title":"Jamb Past Question",
    "instance":instance.year_and_exam_name,
    }
    return render(request, 'past_question/jamb_detail.html', context)

1 个答案:

答案 0 :(得分:1)

views.py

def pdf_view(request):

    # get file path by querying model and then
    with open('/path/to/my/file.pdf', 'rb') as pdf:
        response = HttpResponse(pdf.read(), mimetype='application/pdf')
        response['Content-Disposition'] = 'inline;filename=some_file.pdf'
        return response
    pdf.closed