我想保存来自 youtube 的视频的 url 字段,以便我可以将其加载到我的站点中。到目前为止,我在 html 中想到了这个:
<h3>{{video.title}}</h3>
<object width="425" height="344"><param name="movie" value="{{video.video_url}}"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="{{video.video_url}}" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>
但问题是它只能以一种方式工作。例如:
网址:http://www.youtube.com/watch?v=e4lHTj9xFqE
这仅在 watch?
是 strip 化且 =
变为 /
所以最终的 url 会有点像这样
http://www.youtube.com/v/e4lHTj9xFqE
我正在考虑在保存并替换和删除 url 之前使用正则表达式。我该如何剥离 watch?
,然后将 =
替换为 /
?还有什么更好的方法可以在 html 中加载视频?非常感谢你们的建议。谢谢!
编辑:
模型.py:
class Video(models.Model):
title = models.CharField(max_length=100)
video_url = models.URLField(max_length=100)
def save(self, *args, **kwargs):
new_url = (self.video_url.replace("watch?v=","v/"))
super(Video, self).save(*args, **kwargs)
if new_url:
self.video_url = new_url
最佳答案
为什么使用正则表达式:
string = (r'http://www.youtube.com/watch?v=e4lHTj9xFqE'.replace('watch?','')).replace('=','/')
print string
#http://www.youtube.com/v/e4lHTj9xFqE
但是如果你需要regex给你:
new_url = re.sub('watch\?v=','v/',self.video_url)
编辑:
试试这个:
def save(self, *args, **kwargs):
new_url = re.sub('watch\?v=','v/',self.video_url)
if new_url:
self.video_url = new_url
super(Video, self).save(*args, **kwargs)
不要修改html
关于python - django - 使用正则表达式去除和替换 urlfield,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20512959/