简体   繁体   中英

Opening a user uploaded PDF in django

I have a webapp where a user can upload a pdf file. I want the user to be able to click a button to be able to see the file in the browser.

I'm not sure how to link the pdfs as when they are uploaded they get given a random name by django in my static root. eg: hello_0akcjs.pdf

My View

def pdf_view(request, pk):
    Menufile = Menu.objects.get(pk=pk).menuFile
    with open('Menufile', 'r') as pdf:
        response = HttpResponse(pdf.read(), content_type='application/pdf')
        response['Content-Disposition'] = 'inline;filename=some_file.pdf'
    return response

URL

path('<int:pk>/', pdf_view, name='pdf_view'),

Model

class Menu(models.Model):
    name = models.CharField(max_length=50)
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
    menuFile = models.FileField(upload_to='menus')

Template

{% for menu in menus %}

<a href="{% url 'pdf_view' menu.pk %}" class="btn btn-primary">View Menu {{ menu.name }}</a>

{% endfor %}

As it stands, everything works, except i just dont know how to get the pdf to be rendered at the URL for that model instances PK.

I was making it far too complicated. All i needed to do was reference the menuFile URL in the template.

Example:

<a href="{{ menu.menuFile.url }}" class="btn btn-outline-secondary" style="margin: 2px;">View Menu</a>

To display a pdf you have to use an embed tag,

<embed src={% url 'pdf_view'  menu.pk %} width="500" height="375" type="application/pdf">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM