作为变量的链接无法从模板正确传递到urls.py到views.py

时间:2016-07-04 02:06:32

标签: django

我正在尝试构建一个嵌入了YouTube播放器且加载了默认视频的页面。在侧边栏上,我有一些其他视频的照片。单击其中一个图片时,模板会重新加载,但YouTube播放器现在正在播放另一个视频。这些照片中的每一个都会有一个YouTube网址,点击时需要播放。与任何视频的YouTube页面非常相似。

HTML:

                <div class="col-md-12 col-xs-12 video_menu_item">
            <div class="video_menu_description">
            <a href="/library/videos/" value="https://www.youtube.com/embed/EWrT-aBDxeI" name="para">
                <img src="/images/X.jpg" alt="Video name thumbnail" style="width:60%;height:100px;">
            </a>
            </div>
        </div>  

<div class="video_section_outer">
    <div class="col-md-12 col-xs-12 video_scroll_track">
        <div class="col-md-12 col-xs-12 video_item_outer">
            <h4 class="col-md-12 col-xs-12 video_track_sub_heading"><b>video.v_name</b></h4>
            <div class="col-md-12 col-xs-12 test_button_start">
                <iframe width="420" height="315" src="{{ link }}" frameborder="0" allowfullscreen></iframe>
            </div>
        </div>
    </div>
</div>

URLS.PY:

    from django.conf.urls import include, url
    from django.contrib import admin

    urlpatterns = [

        # Video Sections
        url(r'^library/tests/', 'bt.views.tests', name='tests'),
        url(r'^library/videos-(?P<link1>[\w-]+)/', 'bt.views.videos', {'link': 'para'}),
        url(r'^library/videos/', 'bt.views.videos', name='videos'),
]

VIEWS.PY:

@csrf_exempt
def videos(request, link1 = "https://www.youtube.com/embed/Qj4nEYQA9ks"):
    content = {"link" : link1}
    return render_to_response('videos.html', content)

1 个答案:

答案 0 :(得分:0)

我认为传递整个youtube网址并不理想。您只需将视频ID作为GET参数传递即可简化:

# urls.py
urlpatterns = [
    # Video Sections
    url(r'^library/tests/', 'bt.views.tests', name='tests'),
    url(r'^library/videos/', 'bt.views.videos', name='videos'),
]

# views.py
def videos(request):
    link = 'https://www.youtube.com/embed/{}'.format(
        request.GET.get('id', 'Qj4nEYQA9ks')
    )
    return render_to_response('videos.html', {'link': link})

# videos.html
<a href="{% url 'videos' %}?id=EWrT-aBDxeI">
    <img src="/images/X.jpg" alt="Video name thumbnail">
</a>
<iframe width="420" height="315" src="{{ link }}" frameborder="0" allowfullscreen></iframe>

如果有什么不清楚,请告诉我。