Search code examples
pythondjangoiframeyoutubeembed

Python(Django) - Convert URL from post to a embed YouTube IFrame


Basically what I trying to achive is to find the URL in the post, for example if I post this:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
https://www.youtube.com/watch?v=example 

It will be looking like this: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

YouTube Player

models.py:

from django.db import models

class NewsFeed_Articles(models.Model):
    title = models.CharField(max_length = 120) 
    post = models.TextField()
    date = models.DateTimeField()

def __str__(self):
    return self.title

post.html:

{% extends "Feed/wrapper.html" %}

{% block content %}

  <div class="card">
  <h2 class="text-info">{{newsfeed_articles.title}}</h2>
  <h6 class="text-info">{{newsfeed_articles.date|date:"d-m-Y в H:i:s"}}</h6>
  <p>{{newsfeed_articles.post|safe|linebreaks}}<p>
  <div class="fakeimg" style="height:200px;">Image</div>
  </div>

{% endblock %}

Solution

  • Use the code to convert YouTube URLs to YouTube Embeds:

    import re
    
    def convert_ytframe(text):
      _yt = re.compile(r'(https?://)?(www\.)?((youtu\.be/)|(youtube\.com/watch/?\?v=))([A-Za-z0-9-_]+)', re.I)
      _frame_format = '<iframe width="560" height="315" src="https://www.youtube.com/embed/{0}" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>'
      
      def replace(match):
        groups = match.groups()
        return _frame_format.format(groups[5])
      return _yt.sub(replace, text)
    

    Here's working example you can test it yourself: repl.it/@themisir/AromaticAvariciousMarketing
    Also, you could test Regular Expression here: regex101.com/r/97yhSH/1

    UPDATE

    The code was simplified.

    import re
    
    yt_link = re.compile(r'(https?://)?(www\.)?((youtu\.be/)|(youtube\.com/watch/?\?v=))([A-Za-z0-9-_]+)', re.I)
    yt_embed = '<iframe width="560" height="315" src="https://www.youtube.com/embed/{0}" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>'
    
    def convert_ytframe(text):
      return yt_link.sub(lambda match: yt_embed.format(match.groups()[5]), text)