我想将变量从详细信息方法传递到下载器方法并执行操作。我尝试了几种方法但不起作用
Views.py
from django.shortcuts import render
import pytube
from .forms import VideoDownloadForm
# Create your views here.
def details(request):
if request.method == 'POST':
form = VideoDownloadForm(request.POST, request.FILES)
if form.is_valid():
f = form.cleaned_data['Url']
yt = pytube.YouTube(f) # <-----Pass this 'yt' from here
thumb = yt.thumbnail_url
title = yt.title
return render(request, 'ytdownloader/details.html', {'title': title, 'thumbnail': thumb})
else:
form = VideoDownloadForm()
return render(request, 'ytdownloader/front.html', {'form': form})
def downloader(request): #<----to this method
videos = yt.streams.filter(progressive=True, type='video', subtype='mp4').order_by('resolution').desc().first()
videos.download('C:\\Users\\user\\Downloads')
return render(request, 'ytdownloader/details.html')
details.html
{% extends 'ytdownloader/base.html'%}
{% block content%}
<h1> {{title}}</h1>
<a href="{{thumbnail}}"><img src="{{thumbnail}}" alt=""></a>
<a href="{% url 'download'%}"><button type="submit" class="btn btn-primary ">Download</button></a>
{%endblock%}
最佳答案
基于函数的 View 的行为就像 django 中的Python函数一样,因此如果您需要一个变量(在本例中为yt
),您应该将其传递给函数;您还可以从详细信息
View 中调用downloader
View 及其参数:
def details(request): if request.method == 'POST': form = VideoDownloadForm(request.POST, request.FILES) if form.is_valid(): f = form.cleaned_data['Url'] yt = pytube.YouTube(f) downloader(request, yt) else: form = VideoDownloadForm() return render(request, 'ytdownloader/front.html', {'form': form}) def downloader(request, yt): videos = yt.streams.filter(progressive=True, type='video', subtype='mp4').order_by('resolution').desc().first() videos.download('C:\\Users\\user\\Downloads') thumb = yt.thumbnail_url title = yt.title return render(request, 'ytdownloader/details.html', {'title': title, 'thumbnail': thumb})
关于python - 在 python/django 中将变量从一种方法传递到另一种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59906882/