python - django - 使用正则表达式去除和替换 urlfield

标签 python regex django video youtube

我想保存来自 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

但是如果你需要给你:

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/

相关文章:

python - 将 MKL 链接到 Anaconda 中已安装的 Numpy?

python - 有没有关于 PyQt 库在 Mac OS Big Sur 中不起作用的解决方案?

python - 当特定数量不在特定列中时如何删除数据框的行?

javascript替换问号

python - 最简单的 django 定时/计划任务(例如 : reminders)?

python - django 1.7rc3 和 celery 3.13 - AppRegistryNotReady

python - 如何在绘图中使用自定义png图像标记?

ruby - 在ruby正则表达式中以@符号开头的单词之间插入html标签

regex - 正则表达式中第二个捕获组的一部分

python - 在 django 中通过 SSO + OpenID 对 Google Apps 自定义域的用户进行身份验证