如何生成下载链接

问题描述 投票:0回答:1

我正在尝试创建一个下载文件的链接,该文件已上传。

models.朋友

class Comentario (models.Model):

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

settings.朋友

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

template.html

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

views.朋友

  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.朋友

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

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

谢谢您的回答

python html django file-upload download
1个回答
0
投票

您的问题是您将Comentario对象的Queryset作为“对象”传递给您的模板,但您在模板中根本没有引用“对象”。

下面是一个示例,说明如何为“对象”Queryset中的每个对象提取URL列表。在这里,我们遍历'对象'Queryset中的每个对象,并将其archivo.url拉出到模板中:

comentario_listar.html

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

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

views.朋友

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>
© www.soinside.com 2019 - 2024. All rights reserved.