I've got a page which draws thumbnails of Youtube videos via the google API and I've used Masonry to control said thumbnails & enlarge an element when it's clicked on (at which point I'd like to have the iframe displaying the video).
What I would like to do is render a template containing the iframe & a few extra things for a selected video in the thumbnail element. Trouble is, I'm not great with javascript that isn't clearly found in an example!
At the moment django is setup for non-script users...
My thumbnail page is at /videos/
with each thumbnail rendering the following template;
<div class="video">
<a class="GetYoutubeVideo" data-video-id="{{ object.video_id }}" href="{% url 'show_video' video_id=object.id %}">
{{ object.get_img_tag }}
<span class="title">
<p>{{ object.get_title|slice:":20" }}...</p>
<p class="date">{{ object.date_created|date:"d/m/Y" }}</p>
</span>
</a>
</div>
<script>
$(document).ready(function(){
$(".GetYoutubeVideo").click(function(){
$.ajax({
type: "POST",
dataType: 'json',
url: $(this).attr('href'),
timeout: 5000,
data: {
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
video_id: $(this).attr('data-video-id')
},
success : function(json) {
console.log('Success ' + json);
$('#result').append('Server Response: ' + json.server_response);
},
error : function(xhr, errmsg, err) {
// Currently hits this with an empty `err`
console.log('Ajax Error: ' + errmsg + ' and ' + err);
alert(xhr.status + ": " + xhr.responseText);
}
})
})
});
</script>
With video iframes at /videos/<video_id>/
using the following view;
@never_cache
def show_video(request, page_id=None, video_id=None, **kwargs):
"""
Displays the selected YouTube video.
@type request: HttpRequest
@param request: The HttpRequest object
@type page_id: int
@param page_id: The ID of the page where this video is found
@type video_id: int
@param video_id: The id of the video to display the images of
@rtype: HttpResponse
@return: The rendered template
"""
# Get the VideoGalleryPlugin object
video = get_object_or_404(VideoGalleryPlugin, pk=video_id)
video_data = video.video_data()
return render_to_response('display_video.html',
RequestContext(
request, {
'page_id': page_id,
'video': video,
'video_data': video_data,
}
)
)
Do I need to do something like bind a click event to the thumbnail link with $.ajax
and then have a request.is_ajax()
in show_video()
?
edit
Here's my view as it stands while I'm hitting the error callback in $.ajax()
:
@csrf_exempt
@never_cache
def show_video(request, page_id=None, video_id=None, **kwargs):
# Get the VideoGalleryPlugin object
video = get_object_or_404(VideoGalleryPlugin, pk=video_id)
video_data = video.video_data()
return HttpResponse(
json.dumps({
'page_id': page_id,
'video': serializers.serialize('json', [video, ]),
'video_data': video_data,
}), content_type="application/json"
)