如何生成下载链接

时间:2017-12-17 11:56:41

标签: python html django file-upload download

我正在试图创建一个已下载文件的链接。

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')]

当我点击下载链接时,它不会下载保存在'media'文件夹中的.jpg。路径是否错误指定?有必要为此创建一个特殊视图吗?

感谢您的回答

1 个答案:

答案 0 :(得分:0)

您的问题是,您正在将Comentario对象的Queryset传递给您的模板作为对象&#39;,但您不会引用&#39;对象&#39;完全在你的模板中。

以下是您如何为“对象”中的每个对象提取网址列表的示例。查询集。在这里,我们遍历&#39;对象中的每个对象。 Queryset,并将其archivo.url拉出到模板中:

<强> comentario_listar.html

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

请注意,如果您愿意,还可以将comentario_listar.html传递给单个对象,并像这样呈现该对象的URL:

<强> 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>