Download a PDF in Django

1

Hi, any suggestions to download a pdf file I have the following model where I keep the files:

class Archivo(models.Model):
    archivo_pdf = models.BinaryField(null=True, blank=True)
    nombre = UCharField(max_length=30, null=True, blank=True)

I am trying to download the file as follows:

@login_required
@api_view(['GET'])
def download_file(request,id):
    try:
        archivo = get_object_or_404(Archivo, id=id)
        contents = archivo.archivo_pdf
        name_file = archivo.nombre
        response = HttpResponse(contents)

        response['Content-Disposition'] = 'attachment; filename={}'.format(name_file)

        return response

    except Exception as e:
        if type(e) is Http404:
            return Response(False, status=status.HTTP_404_NOT_FOUND)
        else:
            return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)

When calling the route link , I get the following error message:

  

DjangoUnicodeDecodeError

    
asked by Alexander Morales 21.10.2016 в 00:17
source

2 answers

0

try adding the mimetype in the answer

Like this:

response = HttpResponse(contents, content_type='application/pdf')

    
answered by 21.10.2016 / 05:17
source
1

I have a blog in development and it works wonders for me. in my post app and in the model of it I have class Post (models.Model):

user = models.ForeignKey('auth.User', related_name='posts')
title = models.CharField(max_length=120, verbose_name="título")
content = RichTextField(verbose_name="contenido")
publishing_date = models.DateTimeField(verbose_name="Fecha de Publicacion", auto_now_add=True)
image = models.ImageField(null=True, blank=True)
slug = models.SlugField(unique=True, editable=False, max_length=130)
archivo = models.FileField(blank=True, null=True)

In urls.py of the post I have

from django.conf.urls import url
from .views import *
from post.views import DescargarArchivoView

app_name = "post"

urlpatterns = [

url(r'^index/$', post_index, name="index"),

url(r'^create/$', post_create, name='create'),

url(r'^(?P<slug>[\w-]+)/$', post_detail, name='detail'),

url(r'^(?P<slug>[\w-]+)/update/$', post_update, name="update"),

url(r'^(?P<slug>[\w-]+)/delete/$', post_delete, name='delete'),
url(r'^archivo', DescargarArchivoView.as_view(), name='archivo_post'),
]

In the views.py of my app post I have

from django.views.generic.base import View
class DescargarArchivoView(View):
def post(self, request, *args, **kwargs):
    post = Post.objects.get(pk=request.POST['id_post'])
    response = HttpResponse(post.archivo, content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename="%s"' % post.archivo
    return response

In my template I have the file detail.html and inside

{% if post.archivo %}
        <body>
        <iframe src="url(r'^archivo', DescargarArchivoView.as_view(), name='archivo_post')", frameborder="0"></iframe>
        </body>


        <form method="post" action="{% url 'post:archivo_post' %}">
            {% csrf_token %}

            <input type="hidden" name="id_post" value="{{post.pk}}"/>
            <input type="submit" class="btn btn-primary" type="button" value="Descargar Archivo Adjunto">
        </form>
        {% endif %}
    
answered by 19.02.2018 в 21:14