Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - replace parts of urlfield

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)
like image 510
Robin Avatar asked Oct 02 '22 05:10

Robin


1 Answers

First of all, it seems to be that your url is encoded. Please check if you don't have |urlencode filter in your template (https://docs.djangoproject.com/en/dev/ref/templates/builtins/#urlencode).

To change video URL to playlist URL, you have to use regular expressions. You can create a method which will transform your video URL to playlist URL:

import re
...
def playlist_url(self):
    """
    Generates a playlist URL
    """
    new_url = re.sub(r'^(http:\/\/)([\w\W]+)&list=([\w\W]+)(\&index=[\d]+)$', r'//\2?list=\3', self.video_url)
    return new_url
...
like image 123
Mikhail Chernykh Avatar answered Oct 13 '22 01:10

Mikhail Chernykh