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 about 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' %}
Related
I am using Django Embed Video to upload videos to my website that works perfectly fine. The code below is how I extract the url of the video that I uploaded.
HTML TEMPLATE:
{% for course in courses %}
<div class="name">
<h3>{{course.video}}</h3>
</div>
{% endfor %}
That gives me the url but what i want is the video id for example the url it gives looks like "https://youtu.be/iHkKTGYc6aA" and I just need the "iHkKTGYc6aA". It can be done with the python using the .replace method but whenever I try to use the if tags of django html template i get this error:
Could not parse the remainder:
The HTML code that I use
{% for course in courses %}
<div class="name">
{% if text in course.video %}
<h3>{{url=course.video.replace("https://youtu.be/", "")}} </h3>
{% endif %}
</div>
{% endfor %}
I know it's not the right way of doing it but I shared it just to show what i want to achieve.
My views.py:
def Courses(request):
courses = Video.objects.all()
total_uploaded_videos = courses.count()
text = "https://youtu.be/"
url = ""
context = {'courses':courses, 'total_uploaded_videos':total_uploaded_videos, 'text':text, 'url':url}
return render(request, 'accounts/Course.html', context)
Models.py:
class Video(models.Model):
name = models.CharField(blank=False, max_length=100, default="", null=False, primary_key=True)
video = EmbedVideoField()
def __str__(self):
return self.name
If you have any other way by which I can extract the video id or just the video url (in views.py or models.py) I'll use that instead of the html tags.
course.video.replace("https://youtu.be/", ""),
You can not invoke method with arguments. You need to write a custom filter.
The official guide is here:
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
You want to write a filter replace which removes any string given.
In Project_name/App_name/templatetags, create a blank __init__.py, and replace.py which goes like:
from django import template
register = template.Library()
#register.filter
def replace(value, arg):
return value.replace(arg, "")
In template, use:
{% load replace %} <!-- load templatetag -->
{% for course in courses %}
<div class="name">
{% if text in course.video %}
<h3>{{ course.video|replace:"https://youtu.be/" }}</h3> <!-- value|templatetag:arg -->
{% endif %}
</div>
{% endfor %}
Note: You must restart the server after adding a new templatetag.
I am building a CMS in Mezzanine, and all in all I am extremely impressed with the system. I can't tell you how many CMS systems I have attempted to customize in the past and given up in total frustration.
All in all this has been smooth as silk. But I have a custom page for displaying a YouTube video, and the custom field (which is definitely present in the instance, according to the shell) is failing to render in the template.
The app is called mezz_youtube; here is models.py:
from django.db import models
from django.utils.translation import ugettext_lazy as _
from mezzanine.pages.models import Page, RichText
class YouTubePage(Page):
"""
Implements pages with a YouTube video.
"""
video_slug = models.SlugField(u"video ID", max_length=11)
class Meta:
verbose_name = _("YouTube page")
verbose_name_plural = _("YouTube pages")
The Admin works fine and the YouTubePage was created successfully, as the shell shows:
In [1]: from mezz_youtube.models import YouTubePage
In [2]: p = YouTubePage.objects.get()
In [3]: p.pk
Out[3]: 11
In [4]: p.video_slug
Out[4]: u'CKqGbpR4vvM'
But in the template, as shown here with various debugging entries, the custom field does not appear. Here's the template:
{% extends "pages/page.html" %}
{% load mezzanine_tags %}
{% block main %}
<iframe width="853" height="480" src="http://www.youtube.com/embed/{{ page.video_slug }}" frameborder="0" allowfullscreen></iframe>
<p>Video slug is {% if page.video_slug %}present{% else %}absent{% endif %}.</p>
<p>Title: {{ page.title }} </p>
<p>Model: {{ page.content_model }} </p>
<p>fields:</p>
<ul>
{% for field, val in page.fields.iteritems %}
<li>{{ field }}: {{ val }}</li>
{% endfor %}
</ul>
{{ block.super }}
{% endblock %}
Here is the corresponding section of the output:
<iframe width="853" height="480" src="http://www.youtube.com/embed/" frameborder="0" allowfullscreen></iframe>
<p>Video slug is absent.</p>
<p>Title: ladeda </p>
<p>Model: youtubepage </p>
<p>fields:</p>
<ul>
</ul>
As you can see, the title field renders, but the video_slug field does not. Any idea what is going on here?
I'm an absolute beginner to django (and programming in general), I've tried the django Polls tutorial and all went well, however I am trying to get a minimal voting button to work. Basically I have set up a database with two columns, my models.py looks like this
from django.db import models
class Imgurl(models.Model):
urlvar = models.URLField(max_length=200)# a URL linking to an image
urlvote = models.IntegerField(default=0)# my intended vote count
def __unicode__(self):
return self.urlvar
I have made an input box where I can copy and paste an image url, this image then displays on a separate page(this works fine). What I want is to have a voting button next to each displayed image, where a user can click on the button (I am trying to use a submit button) and the number of votes will increase in the db(no redirecting to a new page, or anything fancy).
I think this is a trivial question and I am trying to learn the basics of POST and database handling in django (also, I have read the relevant chapters in the djangobook... maybe I'm just a little slow?)
my views looks like this
def urlvotes(request):
if request.method=='POST':
if 'voteup' in request.POST:
v=Imgurl(forloop.counter)
v.urlvote +=1
else:
pass
votetotal=v.urlvote # attempt to give the template some kind of context
return render_to_response('display.html', {'votetotal':votetotal}, context_instance=RequestContext(request))
and my template looks like this:
{% extends "base.html" %}
{% block head %}Image display{% endblock %}
{% block content1 %}
Home
{% if links %}
<ul>
{% for link in links %}
<li><img src="{{ link }}"></li>
<li><form action="{% url urlvotes %}" method="post">
{% csrf_token %}
<input type="submit" name="voteup" value='vote'/></p>
<p>{{votetotal}}</p>
</form></li>
{% endfor %}
</ul>
{% else %}
<p>No uploads.</p>
{% endif %}
{% endblock %}
when I run this, as is, I get a csrf verification failed error
Any help would be greatly appreciated
Try adding the #csrf_protect to your view
#csrf_protect
def urlvotes(request):
if request.method=='POST':
if 'voteup' in request.POST:
v=Imgurl(forloop.counter)
v.urlvote +=1
else:
pass
votetotal=v.urlvote # attempt to give the template some kind of context
return render_to_response('display.html', {'votetotal':votetotal}, context_instance=RequestContext(request))
I have the following code that fails to display object images. But displays normal images fine.
My Model
class News(models.Model):
title-----------
image = models.ImageField(upload_to='images')
body------------
Template tag coding
from django import template
register = template.Library()
from ----.models import ---
def funct(num):
myobjects = News.objects.all()[:num]
return {'objects': myobjects}
register.inclusion_tag('news/template.html')(funct)
template coding
{% for object in objects %}
<li>{{ object.title }}</li>
<li><img src="{{ MEDIA_URL }}images/{{ object.image }}" alt="image" /></li>
<li>{{ object.body }}</p></li>
{% endfor %}
This code outputs all the variable information such as title and body in a list however it does not display the associated image. I have tried numerous variations on this code with no success. This is strange because when an image is called from the image folder in the following manner
<img src="{{ MEDIA_URL }}images/star.jpg" />
Everything works fine. The problems occur when its a model image being called.
Any help fixing this issue is much appreciated
This has nothing to do with the custom template tag. If you looked at the source for the rendered page, you would see that {{ object.image }} does not output the URL for the image. You need to use {{ object.image.url }}
I have my photos located on Flickr. I want to sync them between Flickr and my Django app using django-syncr. It's installed, Flickr section is visible in Admin site. I can sync photo data from Flickr to my local database. In a few words -- it works.
But, I don't understand how to get these data from my database using views.py and template file?I mean, how to make my Flickr's photos visible on my site?
I got something like this on my site:
* IMG_2467
* Morning fog on Halong bay
I used these files but get only title from all data and didn't anything else, including photos.
views.py
from django.shortcuts import render_to_response
from syncr.flickr.models import Photo
def index(request):
get_photo = Photo.objects.all()
return render_to_response('index.html', {'get_photo': get_photo})
index.html
<html>
<title>
Test page
</title>
<body>
{% if get_photo %}
<ul>
{% for photo in get_photo %}
<li>{{ photo }}</li>
{% endfor %}
</ul>
{% else %}
<p>No photos are available.</p>
{% endif %}
</body>
</html>
maybe you should add <img src='{{photo.url}}' /> ? I don't see how do you plan to show images if you're just importing the names.