开发者

Using Django to show YouTube videos in templates

I'm attempting to store a list of YouTube links in a model then passing it as a list to a template where it's rendered using YouTube's embed code. Everything seems to be working fine, the variables are passed properly except the videos don't show up. The YouTube iframe code is just blank whereas a copy/pasted of YouTube embed code displays just fine.

The code in the Model:

from django.db import models

class Video(models.Model):
    link = models.URLField()

    def __str__(self):
        return self.link                            

The code in the View:

def index(request):
    full_list = Video.objects.all()
    return render_to_response('index.html', {'full_list': full_list})

The code in the Template:

<h1>YouTube list</h1>
{% if full_list %}
    <ul>
    {% for video in full_list %}
        <li>
<!-- link passed to embed code, this shows up as blank -->
<iframe width="560" height="345" src="{{ video.link }}?rel=0" frameborder="0" allowfullscreen></iframe>

<!-- YouTube embed link copy/pasted as is -->
<iframe width="560" height="345" src="http://www.youtube.com/embed/vLmNvYTTWXM?rel=0" frameborder="0" allowfullscreen></iframe>
        </li>
    {% endfor %}
    </ul>
{% else %}
    <p>No videos available</p>
{% endif %}

Screenshot of the browser: https://img.skitch.com/20110910-t78bm288mxh6nmyjmcbxyjr37n.png

I'm guessing that the templates are rendered first and the variable is added second hence YouTube's server is not even called. Is this a correct assumption and if so how do I go abou开发者_StackOverflowt fixing it?


Your code is correct as I can see. Mb you will show us result html code? The only thing thay may be wrong is lack of __unicode__ method in your model. You should use not __str__ but __unicode__.


I wrote a template tag, which does exactly what's needed above.

https://gist.github.com/chhantyal/5396911


You could use this library to make your life easier:

https://github.com/jazzband/django-embed-video

Embed Videos the Easiest Way:

models.py

from django.db import models
from embed_video.fields import EmbedVideoField

class Item(models.Model):
    video = EmbedVideoField()  # same like models.URLField()

template

{% load embed_video_tags %}

The video tag:
{% video item.video as my_video %}
  URL: {{ my_video.url }}
  Thumbnail: {{ my_video.thumbnail }}
  Backend: {{ my_video.backend }}

  {% video my_video "large" %}
{% endvideo %}

Or embed shortcut:
{% video my_video '800x600' %}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜