我觉得我已经接近成功了。我什么都累了,但录像没有显示出来。我认为问题在于HTML。
型号:
class Video(models.Model):
link = models.URLField()
def video_id(link):
query = urlparse(link)
if query.hostname == 'youtu.be':
return query.path[1:]
if query.hostname in ('www.youtube.com', 'youtube.com'):
if query.path == '/watch':
p = parse_qs(query.query)
return p['v'][0]
if query.path[:7] == '/embed/':
return query.path.split('/')[2]
if query.path[:3] == '/v/':
return query.path.split('/')[2]
def __unicode__(self):
return self.link
视图:
def index(request):
full_list = Video.objects.all()
return render_to_response('index.html', {'full_list': full_list})
HTML:
{%load staticfiles %}
{%load static%}
<h1>YouTube list</h1>
{% if full_list %}
<ul>
{% for video in full_list %}
<li>
<iframe width="560" height="345" src="{{Video.video_id}}?rel=0" frameborder="0" allowfullscreen></iframe>
</li>
{% endfor %}
</ul>
{% endif %}
我已经做了三天了,我似乎不能让视频出现。
发布于 2018-03-31 04:14:43
尽管您已经在Video
类中创建了一个函数,但是您并没有将"self“作为第一个参数传递。此外,您还试图将其作为属性访问,而不是作为模板上的函数进行访问。
固定代码应该如下所示:
# Model:
class Video(models.Model):
link = models.URLField()
@property
def video_id(self):
query = urlparse(self.link)
if query.hostname == 'youtu.be':
return query.path[1:]
if query.hostname in ('www.youtube.com', 'youtube.com'):
if query.path == '/watch':
p = parse_qs(query.query)
return p['v'][0]
if query.path[:7] == '/embed/':
return query.path.split('/')[2]
if query.path[:3] == '/v/':
return query.path.split('/')[2]
def __unicode__(self):
return self.link
然后,稍后在模板上使用它,就像在属性上使用它一样:
<iframe width="560" height="345" src="{{Video.video_id}}?rel=0" frameborder="0" allowfullscreen></iframe>
否则,您可以使它成为一个函数:
# Model:
class Video(models.Model):
link = models.URLField()
def video_id(self):
query = urlparse(self.link)
if query.hostname == 'youtu.be':
return query.path[1:]
if query.hostname in ('www.youtube.com', 'youtube.com'):
if query.path == '/watch':
p = parse_qs(query.query)
return p['v'][0]
if query.path[:7] == '/embed/':
return query.path.split('/')[2]
if query.path[:3] == '/v/':
return query.path.split('/')[2]
def __unicode__(self):
return self.link
但是,您需要将其作为一个函数调用:
<iframe width="560" height="345" src="{{Video.video_id()}}?rel=0" frameborder="0" allowfullscreen></iframe>
https://stackoverflow.com/questions/49584132
复制相似问题