Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何查询与外键相关的文件字段_Python_Django_Models - Fatal编程技术网

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

Python 如何查询与外键相关的文件字段,python,django,models,Python,Django,Models,大家好,我一直在尝试用foreignkey查询文件,但这不起作用,django抛出了一个错误,我已经尝试了很长时间,现在我刚刚给出了答案,现在我又回到了需要帮助的地方 from __future__ import unicode_literals from django.db import models class Examination(models.Model): examination_name = models.CharField(max_length=50, un

大家好,我一直在尝试用foreignkey查询文件,但这不起作用,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)

视图中.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

包括您的视图。py我不知道如何渲染pdf。因为我是从django admin.com上传的,所以我必须指定要显示的文件吗?因为我不打算只显示一个pdf文件,如图所示,我正在从我的模型上传很多文件,我想显示文件名,然后我将在浏览器中呈现pdf。文件\u name=models.CharField(max\u length=40,default='self'),然后我将显示pdf文件。是的,您需要指定文件。但我将查询大量文件。比如通过id=id得到一个帖子。。。。。。?我在这里有点困惑。你可以创建一个动态路径并使用动态文件名。你可以使用
/path/to/my/file.pdf
而不是
'/path/'+dynamicfilename
然后传递它。