Django - replace parts of urlfield

Viewed 459

I can now load single video URLs of youtube. But the problem now is to load the playlist videos of youtube. So my question is, how do I replace two same pattern, but both having different replacements of a url?

Eg:

Actual url:

<iframe width="400" height="327" src="http://www.youtube.com/embed/1UiICgvrsFI&amp;list=PLvAOICvbvsbnc5dLG0YR9Mq_tFfzAhQSp&amp;index=1" allowfullscreen="true"></iframe>

Replace the pattern to become like this:

<iframe width="560" height="315" src="//www.youtube.com/embed/1UiICgvrsFI?list=PLvAOICvbvsbnc5dLG0YR9Mq_tFfzAhQSp" allowfullscreen></iframe>

Here the first &amp; changes to ? and the second &amp; and its following contents i.e. &amp;index=1 are stripped.

This is the models.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

Edit:

def save(self, *args, **kwargs):
        new_url = re.sub('watch\?v=','embed/',self.video_url)
        new_url = re.sub(r'^(http:\/\/)([\w\W]+)\&amp;list=([\w\W]+)(\&amp;index=[\d]+)$', r'//\2?list=\3', new_url)
        if new_url:
            self.video_url = new_url
            super(Video, self).save(*args, **kwargs)
2 Answers
Related