【发布时间】:2020-11-28 17:31:13
【问题描述】:
我有我的 django 应用程序,它搜索 youtube 并将结果作为字典返回,我将它们呈现在模板中,返回值之一是链接,现在我有一个下载按钮,我希望它的功能是每当你点击按钮它应该获取点击结果的 url,并将其作为参数传递给另一个下载函数。我该如何做到这一点?
这是我的观点.py
def index(request):
if request.method == 'POST':
query = request.POST['video_name']
n = 12
search = SearchVideos(str(query), offset = 1, mode = "json", max_results = n)
ytresults = search.result()
result_dict = json.loads(ytresults)
context = {
"result" : result_dict,
}
template_name = "youloader/results.html"
return render(request, template_name, context)
else:
query = "no copyright sound"
n = 12
search = SearchVideos(str(query), offset = 1, mode = "json", max_results = n)
index_results = search.result()
result_dict = json.loads(index_results)
context = {
"result" : result_dict
}
template_name = "youloader/index.html"
return render(request, template_name, context)
def downloading_video(request):
try:
with youtube_dl.YoutubeDL(video_opts) as ydl:
ydl.download(link)
except:
pass
这是我的模板.html
<div class="my-4" >
<div style="padding-top: 20px">
<div class="row" >
{% for result in result.search_result %}
<div class="col-12 col-sm-6 col-md-4 col-lg-4">
<div class="card shadow-sm border-0 my-2">
<img src="{{ result.thumbnails.1 }}" alt="{{ result.channelId }}">
<div class="card-body">
<h5 class="card-title">{{ result.link }}</h5>
<div class="d-flex flex-wrap justify-content-between card-subtitle my-2 text-muted small">
<a href="{{ result.link }}" class="text-secondary font-weight-bold">
<i class="fa fa-tablet mr-1"></i>{{ result.channel }}
</a>
<span><i class="fa fa-stopwatch mr-1"></i>{{ result.duration }}</span>
<span><i class="fa fa-eye mr-1"></i>{{ result.views }}</span>
<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">Download</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">Audio</a>
<a class="dropdown-item" href="#">Video</a>
</div>
<br>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
这是渲染模板的示例。
【问题讨论】:
-
你想把索引函数的链接导出到download_video函数吗?
-
是的,这正是我想要的。 @RezaGH
-
通过调用 download_video() 定义启动下载的 URL。按下按钮时发布下载链接。
标签: python django django-views django-templates youtube-dl