How to generate download link?

Question:

I’m triying to create a link to download file which has been uploaded.

models.py

class Comentario (models.Model):

    archivo = models.FileField(upload_to='media', null=True, blank=True)

settings.py

MEDIA_ROOT=os.path.join(BASE_DIR, 'media')
MEDIA_URL='/media/'

template.html

<a href="{{ MEDIA_URL }} {{detail.archivo.url}}" download>Descargar</a>

views.py

  def ComentarioListar(request):
     form2 = ComentarioForm(request.POST or None, request.FILES or None)
     if request.method == 'POST' and form2.is_valid():
        form2.instance.autor = request.user
        form2.save()
        return HttpResponseRedirect('http://127.0.0.1:8000/home/listar')

objects= Comentario.objects.filter(tag__in=bb).exclude(autor__id=request.user.id)[:5]

return render(request, 'home/comentario_listar.html', {'objects': objects,  'form2':form2})

urls.py

urlpatterns = [
    url(r'^download/(?P<filename>.+)$', login_required(views.download), name='download')]

When I click the download link it does not download the .jpg saved in ‘media’ folder. Is the path incorrectly specified? It is necessary to create a special view for that?

Asked By: JohnWire

||

Answers:

Your problem is that you are passing a Queryset of Comentario objects through to your template as ‘objects’, but you then aren’t referencing ‘objects’ at all in your template.

Here’s an example of how you could pull a list of URLs for each object in your ‘objects’ Queryset. Here, we iterate through each object in the ‘objects’ Queryset, and pull its archivo.url out into the template:

comentario_listar.html

{% for object in objects %}
    <a href="{{ object.archivo.url }}">Descargar</a>
{% endfor %}

Note that if you wanted, you could also pass comentario_listar.html a single object and render that object’s URL like so:

views.py

def ComentarioListar(request):
     form2 = ComentarioForm(request.POST or None, request.FILES or None)
     if request.method == 'POST' and form2.is_valid():
        form2.instance.autor = request.user
        form2.save()
        return HttpResponseRedirect('http://127.0.0.1:8000/home/listar')

    // Create a variable called 'detail' that references just one Comentario object, and pass it to the comentario_listar.html template
    detail = Comentario.objects.all()[0]

    return render(request, 'home/comentario_listar.html', {'detail': detail,  'form2':form2}

comentario_listar.html

<a href="{{detail.archivo.url}}" download>Descargar</a>
Answered By: Sam