Vaibhav Vishwakarma
Vaibhav Vishwakarma

Reputation: 91

How can I extract URL of the video uploaded using Django Embed video

I am using Django Embed Video to upload videos to my website that works perfectly fine. The code below is how I extract the url of the video that I uploaded.

HTML TEMPLATE:

{% for course in courses %}
<div class="name">
<h3>{{course.video}}</h3>
</div>
{% endfor %}

That gives me the url but what i want is the video id for example the url it gives looks like "https://youtu.be/iHkKTGYc6aA" and I just need the "iHkKTGYc6aA". It can be done with the python using the .replace method but whenever I try to use the if tags of django html template i get this error:

Could not parse the remainder: 

The HTML code that I use

{% for course in courses %}
    <div class="name">
        {% if text in course.video %}
            <h3>{{url=course.video.replace("https://youtu.be/", "")}} </h3>
        {% endif %}
    </div>
{% endfor %}

I know it's not the right way of doing it but I shared it just to show what i want to achieve.

My views.py:

def Courses(request):
    courses = Video.objects.all()

    total_uploaded_videos = courses.count()

    text = "https://youtu.be/"
    url = ""


    context = {'courses':courses, 'total_uploaded_videos':total_uploaded_videos, 'text':text, 'url':url}

    return render(request, 'accounts/Course.html', context)

Models.py:

class Video(models.Model):
    name = models.CharField(blank=False, max_length=100, default="", null=False, primary_key=True)
    video = EmbedVideoField()  

    def __str__(self):
        return self.name

If you have any other way by which I can extract the video id or just the video url (in views.py or models.py) I'll use that instead of the html tags.

Upvotes: 0

Views: 736

Answers (1)

Sumeth Sathnindu
Sumeth Sathnindu

Reputation: 343

course.video.replace("https://youtu.be/", ""), You can not invoke method with arguments. You need to write a custom filter.

The official guide is here:

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

You want to write a filter replace which removes any string given.

In Project_name/App_name/templatetags, create a blank __init__.py, and replace.py which goes like:

from django import template

register = template.Library()

@register.filter
def replace(value, arg):
    return value.replace(arg, "")

In template, use:

{% load replace %} <!-- load templatetag -->

{% for course in courses %}
    <div class="name">
        {% if text in course.video %}
            <h3>{{ course.video|replace:"https://youtu.be/" }}</h3> <!-- value|templatetag:arg -->
        {% endif %}
    </div>
{% endfor %}

Note: You must restart the server after adding a new templatetag.

Upvotes: 1

Related Questions