Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I render a view from a predefined list/dict, instead of from a database id, in django?
I'm curious if I can render a view directly from a list (or dictionary) in Django instead of from a model, and thus programmatically generate pages based on the corresponding template (here, my_template.html). I've done this many times after creating a model whereby the <str:my_list> would reference the corresponding database in. In a use-case that involves an API call though, I'd rather not go the database route as it becomes somewhat redundant. I'm sure it has to be possible, but I seem to be going in circles trying to execute it. urls.py # ... urlpatterns = [ # ... path('path/<str:my_list>', views.my_view, name='my_view'), ] views.py # ... def my_view(request, my_list): return render(request, 'core/my_template.html') A list could be something as simple as: my_list = [ item_1, item_2, # ... ] Thanks! -
Django model error is unboundPylance (reportUnboundVariable)
I have a model class in Django model.py. like as class EmployInfo(models.Model): password = models.OneToOneField(User, on_delete=models.CASCADE) designation = models.ForeignKey(UserRole, on_delete=models.CASCADE) user_basic = models.OneToOneField(EmployBasicInfo, on_delete=models.CASCADE) user_academic = models.OneToOneField(EmployAcademicInfo, on_delete=models.CASCADE) user_address = models.OneToOneField(EmployAddressInfo, on_delete=models.CASCADE) def __str__(self): return self.user_basic.name I do query object from EmployInfo like as @api_view(['put']) @permission_classes([IsAuthenticated]) @edit_required def employ_update(request, pk): employ_user = EmployInfo.objects.get(id=pk) pass But This error local variable 'EmployInfo' referenced before assignment occurs. why this error occurs I can not understand. pls, help me to solve the problem... -
Change column name to current month
I have a snippet of the following template <div class="table-responsive-sm" style="overflow:scroll"> <table class="table table-striped table-bordered table-hover" id="example"> <thead class="thead-dark"> <tr> <th colspan="2" scope="colgroup">Student grades</th> </tr> <tr> <th colspan="1">Grade1</th> <th colspan="1">Grade2</th> </tr> <tr> <th colspan="1">Current Month</th> <th colspan="1">Previous Month</th> </tr> Does anybody know, how to change 'Current Month' and 'previous Month' into the actual current month (in letters) and actual previous month (also in letters)? I didn't include any code from my views.py because I had nothing written on it yet because I don't know how to change it. -
Tags input field in instance view at admin panel
I'm using django-taggit and its working fine, but one moment. When i open instance in django admin - tags input field autofill with following format: 1 is it possible to get tags input autofill format like this? 2 Or disable autofill by default? Django version 1.9, django-taggit 1.3.0 admin.py 3 -
How long does the event_loop live in a Django>=3.1 async view
I am playing around with the new async views from Django 3.1. Some benefits I would love to have is to do some simple fire-and-forget "tasks" after the view already gave its HttpResponse, like sending a push notification or sending an email. I am not looking for solutions with third-party packages like celery! To test this async views I used some code from this tutorial: https://testdriven.io/blog/django-async-views/ async def http_call_async(): for num in range(1, 200): await asyncio.sleep(1) print(num) # TODO: send email async print('done') async def async_view(request): loop = asyncio.get_event_loop() loop.create_task(http_call_async()) return HttpResponse("Non-blocking HTTP request") I started the django server with uvicorn. When I make a request to this view it will immediately return the HTTP-response "Non-blocking HTTP request". In the meantime and after the HTTP-response, the event loop continues happily to print the numbers up to 200 and then print "done". This is exactly the behaviour I want to utilize for my fire-and-forget tasks. Unfortunatly I could not find any information about the lifetime of the event loop running this code. How long does the event loop live? Is there a timeout? On what does it depend? On uvicorn? Is that configurable? Are there any resources which discuss this topic? -
Django allow user to select session timeout duartion
I want the users or the user admin in my Django application to be able to chose the session timeout duration. I know session timeout can be configured in settings.py but what if i want to give users the ability to chose session timeout duration on the GUI/frontend? -
How can I get editor instance by id? (page has multiple jsoneditor objects)
I am working on integrating JSONEditor into the Django project like a widget for json field. So on one page, I have several JSON instances, but the function onChange works only for the last instance JSONeditor . That is my template: <div id="{{ name }}_editor" style="width: 400px; resize:vertical"></div> <textarea cols="40" id="id_{{ name }}" name="{{ name }}" rows="10" style="display: none">{{ data }}</textarea> <script> var container = document.getElementById("{{ name }}_editor"); var options = { mode: 'code', modes: ['code', 'form', 'text', 'tree', 'view', 'preview'], onError: function (err) { alert(err.toString()); }, onChange(value) { var json = JSONEditor.get(); container.value=JSON.stringify(json); }, }; json = {{ data|safe }}; var editor = new JSONEditor(container, options); editor.set(json) </script> Can I get JSONEditor object by id in onChange?( editor.aceEditor.id) thanks! -
Filtering dropdowns of SubCategories that are in specific Categories
I'm learning django and I have trouble. In django admin panel, when I add product and choose category and subcategory, I see all subcategories of all categories. This is a problem because in my app there can be a lot of similiar SubCategories. The image! I've read a lot of similiar answers, docs in the internet but all the solutions didnt help me (or I'm stupid and did it wrong). Here are my models.py: class Category(models.Model): name = models.CharField('Название',max_length=255) slug = models.SlugField('Ссылка', unique=True) class Sub_Category(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField('Название', max_length=255) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) sub_category = models.ForeignKey(Sub_Category, on_delete=models.CASCADE) title = models.CharField('Название товара:', max_length=50) slug = models.SlugField(unique=True) I will be so grateful if you help me to understand this thing! -
How to update field in model connected via foreign key
I'm working on update view where I want to update size of tshirt by click on the item on Order view list. I stacked in point where I can only display name of item but not update size of tshirt. This is django 3. Please some hint, how I can update size of tshirt connected by foreign key with Order model. models.py class Size(models.TextChoices): SMALL = 'S', 'Small' c = 'M', 'Medium' LARGE = 'L', 'Large' class Tshirt(models.Model): name = models.CharField(max_length=255) size = models.CharField(max_length=2, choices=Size.choices, default=Size.MEDIUM) def __str__(self): return self.name class Order(models.Model): nr = models.PositiveIntegerField(unique=True) item = models.ForeignKey(Tshirt, related_name='order_tshirts', on_delete=models.CASCADE) send_date = models.DateTimeField(null=True, blank=True) def get_update_size_url(self): return reverse('size_update', kwargs={'pk': self.pk}) urls.py path('update/<int:pk>/', TshirtSizeUpdateView.as_view(), name='size_update'), views.py class TshirtSizeUpdateView(UpdateView): model = Order template_name = 'size_update.html' fields = ['item'] success_url = '/' forms.py class OrderForm(forms.ModelForm): class Meta: model = Order fields = '__all__' ``` -
How do I obtain a string with special characters line'<','>' that are filled into forms in django
I'm using a form to read inputs. The form.py looks like this from django import forms class Form_info(forms.Form): file_format = forms.CharField(label='file format :', help_text='Write the fields in the file within square brackets along with other special characters that occur') file_format field takes inputs like : <Date> <Time> <CustomerName>: [<Payment>]. I want to retrieve a this string in the view.py file. My current views.py file has a method forms_info that handles the form: def forms_info(request): if request.method = "POST": form = Form_info(request.POST) if form.is_valid(): file_format = form.cleaned_data['file_format'] return HttpResponse('<p>file_format : {}</p>'.format(file_format)) return render(request,"form.html",{}) When I fill the form with '<Date> <Time> <CustomerName>: [<Payment>]', the results printed look like this : file_format : : [] It looks like the input between the angular brackets aren't being read. And this is happening only for some characters like '<','>'. Is there any way that I can directly get this entire string : '<Date> <Time> <CustomerName>: [<Payment>]'? Thanks in advance. -
Django model save the form but does not show me
Hi I have created a address model and link that model to the forms and created the view. but that form does save any data but that data does not show to me. Although it show me that data in the terminal .This is how my admin look like:admin here is my address model.address model and my billing model is which I inherit here is: billing model and my form for address model is:address form my view for addresses isaddress view: the form is showing on checkout so the checkout view is: cart view now my form.html is: form html and my checkout html is: {% extends 'base.html' %} {% block content %} {{object.order_id}} -- {{object.cart}} {% if not billing_profile %} <div class="row text-center"> <div class="col-12 col-md-6"> <p class="lead">Login</p> {% include 'accounts/snippets/form.html' with form=login_form next_url=request.build_absolute_uri %} </div> <div class="col-12 col-md-6"> <p class="lead">Continue as guest</p> {% url "guest_register" as guest_register_url %} {% include 'accounts/snippets/form.html' with form=guest_form next_url=request.build_absolute_uri action_url=guest_register_url %} </div> </div> {% else %} {% if not object.shipping_address %} <div class="row"> <div class="col-md-6 mx-auto col-10"> <p class="lead">Shipping Address</p> {% url "checkout_address_create" as checkout_address_create %} {% include 'addresses/form.html' with form=address_form next_url=request.build_absolute_uri action_url=checkout_address_create address_type='shipping' %} </div> </div> {% elif not object.billing_address%} <div class="row"> … -
reduce line of code while fetching data from object to object?
I am creating a printing ordering service website in Django and I am stuck on the order page. I have three tables named "product" ,"size", and "sizeProductMap" table. views.py products = Product.objects.get(prod_ID=id) print(products.prod_Name) sizesmap = SizeProductMapping.objects.filter(prod_id=id) sizeslist = [] for data in sizesmap: sizes = data.size_id sizeslist.append(sizes.prod_size) # Here I am getting all the sizes I needed. print(sizes.prod_size) return render(request, "GalaxyOffset/product.html", {'products': products, 'sizeslist': sizeslist}) product.html {% extends 'GalaxyOffset\basic.html' %} {% block title%}Products{% endblock %} {% block body%} <div class="card my-2 mx-0 auto"> <div class="mx-4 my-2"> <h1>{{ products.prod_Name }}</h1> </div> <div class="row"> <div class="col-3"> <img class="border border-secondary my-4 mx-4" height="200" src="{{products.prod_img.url}}" width="200"/> </div> <div class="col-8 my-4"> <p> {{products.prod_Desc}}</p> </div> <div class="dropdown-divider"></div> </div> </div> <div class="row"> <div class="col-4"> <div class="card mx-2 my-2 border border-secondary"> <div class="mx-2 mt-4"> {% for category in categories %} <a id="{{ category.prod_ID }}" class="dropdown-item" href="{% url 'product' category.prod_ID%}"> {{ category.prod_ID }}. {{ category.prod_Name }}</a> <div class="dropdown-divider"></div> {% endfor %} </div> </div> </div> <div class="col-8"> <div class="card mx-2 my-2"> <div class="my-2"> <!-- How can I reduce Number of Line of code here. --> {% for s in sizeslist %} <input type="radio" name="sizes">{{s}} </br> {% endfor %} </div> </div> </div> </div> {% endblock %} Can you help me here … -
Validation error with DRF PointField - "Enter a valid location"
In one of my APIs, I am able to get the DRF extra field, PointField working. In one of the other API where I am using PointField in a nested serializer, it is giving me a validation error. { "booking_address": { "coordinates": [ "Enter a valid location." ] } } And the payload data is { "booking_address": { "coordinates" : { "latitude": 49.87, "longitude": 24.45 }, "address_text": "A123" } } My serializers are below: BookingSerializer class BookingSerializer(FlexFieldsModelSerializer): booked_services = BookedServiceSerializer(many=True) booking_address = BookingAddressSerializer(required=False) ------ def validate_booking_address(self, address): if address.get("id"): address = BookingAddress.objects.get("id") else: address["customer"] = self.context.get("request").user.id serializer = BookingAddressSerializer(data=address) if serializer.is_valid(): <---- error is coming from here address = serializer.save() else: raise ValidationError(serializer.errors) return address My Address Serializer is defined as: class BookingAddressSerializer(FlexFieldsModelSerializer): coordinates = geo_fields.PointField(srid=4326) customer = serializers.IntegerField(required=False) And booking model is: class BookingAddress(BaseTimeStampedModel): customer = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="booking_addresses", on_delete=models.CASCADE) coordinates = models.PointField() address_text = models.CharField(max_length=256) Tried Debugging, been stuck here for a few hours now and not able to find the issue. Any help will be appreciated. -
Django FilePathField throwing a TypeError
When a candidate submits a job application, I want the CV field on the application model to point to the CV that the candidate has saved on their profile. models.py def cv_path(instance): return os.path.join(settings.MEDIA_ROOT, 'candidates/user_{0}'.format(instance.candidate.user.id)) def user_directory_path(instance, filename): return 'candidates/user_{0}/{1}'.format(instance.user.id, filename) class Candidate(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True) cv = models.FileField(upload_to=user_directory_path, default="CV to be added") def __str__(self): return f"{self.user.first_name} {self.user.last_name}" class Application(models.Model): candidate = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) job = models.ForeignKey('Vacancy', on_delete=models.CASCADE) cv = models.FilePathField(path=cv_path, default=None) cover_letter = models.TextField(default=None, validators=[ MinLengthValidator(0), MaxLengthValidator(2000) ]) submitted = models.DateTimeField(auto_now_add=True) is_succesful = models.BooleanField(default=False) Right now, if I try to add an application from the admin site I get this TypeError: TypeError at /admin/recruit/application/add/ cv_path() missing 1 required positional argument: 'instance' However if I change the cv_path to this: def cv_path(): return os.path.join(settings.MEDIA_ROOT, 'candidates/user_2') I do not get any error and the cv field gives me a dropdown of all the CV's saved for the user with an id of 2 but of course I cannot hardcode this. How can I fix this error? -
Django dynamic menu in navbar
I want to create dynamic menu, means that menu load from table Here is menu setup in my django admin panel and here is how i create or setup a menu And this is the current result def process_request(self, request): html_menu = '' menus = menu.Menu.objects.order_by('order_number').all() used_ids = [] for m in menus: print(">>>>>> " , m, m.children_menu.all()) if m.target_url == '' or m.target_url is None or m.target_url == '#': menu_link = '#' else: menu_link = reverse(m.target_url) children = m.children_menu.all() if len(children) > 0: children_ids, children_html_menu = self.recursive_menu(m, children) html_menu += children_html_menu used_ids += children_ids elif m.is_divider: html_menu += f''' <hr class="sidebar-divider"> <div class="sidebar-heading"> {m.title} </div> ''' elif m.id not in used_ids: html_menu += f''' <li class="nav-item active"> <a class="nav-link" href="{menu_link}"> <i class="{m.icon_class}"></i> <span>{m.title}</span> </a> </li> ''' used_ids.append(m.id) print(html_menu) request.menus = html_menu def recursive_menu(self, m, children): print("test " , m, children) children_ids = [] html_menu = f''' <li class="nav-item"> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapse{m.order_number}" aria-expanded="true" aria-controls="collapse{m.order_number}"> <i class="{m.icon_class}"></i> <span>{m.title}</span> </a> <div id="collapse{m.order_number}" class="collapse" aria-labelledby="headingUtilities" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> ''' if len(children) < 1: return children_ids, html_menu else: for c in children: # print(c, ">>>>>>>>>..", c.children_menu) children_ids.append(c.id) if c.target_url == '' or c.target_url is None or c.target_url == … -
How to get real password from Django rest framework ( JWT token ). For UserListView
I'm new to this topic, I want to implement the output of users and their real passwords for admin access. At the moment I have this code, it displays encrypted passwords. How can I make the password that the user entered during registration appear in the field? Thank you in advance. class UserListView(generics.ListAPIView): queryset = models.User.objects.all() serializer_class = serializers.UsersListSerializer class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(('email address'), unique=True) first_name = models.CharField(('first name'), max_length=30, blank=True) last_name = models.CharField(('last name'), max_length=30, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return str(self.email) def save(self, *args, **kwargs): super(User, self).save(*args, **kwargs) return self @property def token(self): return self._generate_jwt_token() def _generate_jwt_token(self): dt = datetime.now() + timedelta(days=60) token = jwt.encode({ 'id': self.pk, 'exp': dt.utcfromtimestamp(dt.timestamp()) }, settings.SECRET_KEY, algorithm='HS256') return token.decode('utf-8') class UserManager(BaseUserManager): def _create_user(self, first_name, last_name, email, password=None, is_active=True, is_staff=False, is_superuser=False): if not first_name: raise ValueError('First name should be set') if not last_name: raise ValueError('Last name should be set') if not email: raise ValueError('Email should be set') user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, is_active=is_active, is_staff=is_staff, is_superuser=is_superuser ) user.set_password(password) user.save(using=self._db) return user def create_user(self, first_name, last_name, email, password=None): user = self._create_user(first_name, last_name, email, password=password, is_staff=True) return … -
how do I make toasts push messages if there's any
So some of the toasts are working fine how it's supposed to except some "class-based toasts" aren't working, like the 'warning toast' and 'info toast'(sometimes). I want them to show up for a certain time and then make them disappear and all of them should work the same. I tried compiling the javascript code in Babel but still doesn't work, no clue what's causing the situation. Thnx for any help! Getting a console error as such "messages.js:4 Uncaught TypeError: Cannot read property 'style' of null at showToast (messages.js:4) at messages.js:17" let margin = 10; const showToast = (type) => { const toast = document.getElementById(`toast-${type}`); toast.style.display = 'block'; toast.style.marginBottom = `${margin}px`; margin += toast.clientHeight + 5; hideToast(toast); } const hideToast = (toast) => { setTimeout(() => { toast.style.display = 'none'; margin -= toast.clientHeight + 5; }, 2000); } showToast('success'); showToast('info'); showToast('warning'); showToast('error'); .success{ display: none; position: fixed; bottom: 0; margin-bottom: 10px; margin-left: 4%; font-family: Arial; padding: 15px; background-color: forestgreen; color: #FFFFFF; border-radius: 10px; text-align: center; z-index: 2; box-shadow: 0 0 20px rgba(0,0,0,0.3); } .info{ display: none; position: fixed; bottom: 0; margin-bottom: 10px; margin-left: 4%; font-family: Arial; padding: 15px; background-color: blue; color: #FFFFFF; border-radius: 10px; text-align: center; z-index: 2; box-shadow: 0 0 … -
Use `throttle_classes` for spyne application for set rate limit
I have used spyne library for my django rest framework application for incoming XML data. Now i want to implement throttle_classes for set rate limit in order to avoid heavy incoming request load on my server. I have tried this code to use permission_class in URL for spyne application, but it is not working. remove authentication and permission for specific url path url( r"^vapi/", (permission_classes([IsAuthenticated])(vapi_view.vapp)).as_view(application=vapi_view.vapp), ), This one is from django view which is working fine. url(r'^test/$', (permission_classes([IsAuthenticated])(algo_program_views.TestView)).as_view()), I have also tried to use that in Service Class as a decorator, which is also not working. class HelloWorldService(Service): @api_view(['POST']) @permission_classes([IsAuthenticated]) @rpc(Unicode, Integer, _returns=Iterable(Unicode)) def say_hello(ctx, name, times): for i in range(times): yield 'Hello, %s' % name -
How to enable Forms in Django Rest Framework's Browsable API on production?
I'd like to set DEBUG = False in Django, while preserving full Django Rest Framework's Browsable API functionality. I'd like to preserve full functionality for whitelisted IP addresses only. This is how it looks like when DEBUG = True is set: DebugTrue Forms are displayed and working (Raw data and HTML form tabs) Extra actions and OPTIONS buttons are working JSON highlighting is active. I'd like to preserve this functionality on production (for whitelisted IP addresses only). As soon as I set DEBUG to False, I lose it. This is how it looks like when DEBUG = False is set: DebugFalse No forms are displayed Extra actions and OPTIONS buttons are not working JSON highlighting isn't active How to force activate these DRF features while leaving Django in DEBUG = False mode? I'd like to have these features enabled for whitelisted IP addresses. How to achieve this? Thank you! -
Django: detect what models was used in query
TL;DR: Need to know what models was used in queries executed in some block of code I have self-made caching system that has ability to automatically drop cache when specific models get saved. The usage is (example in Django Rest framework API viewset): class UsersViewSet(ListModelMixin) model = User queryset = User.objects # Here cache decorator goes @cache_view(models_to_drop_cache=[User, UserProfile, UserPhone]) def list(self, request, *args, **kwargs): # calling the real viewset method return super().list(request, *args, **kwargs) Now when any of models [User, UserProfile, UserPhone] change, cache on that view would be dropped (it's achieved by using signal receiver of model save signal). The problem is: sometimes not all models got written to the list (somebody forgot to) and cache not being dropped when it should. I want to add some debug argument to method cache_view so in debug mode decorator gather information about models that was used in the decorated method and output the list. I've tried to look for model signals but didn't succeeded. It seems like I need to monkey-patch Django's query builder to check for table names in resulting SQL code that got executed. Maybe there is more straightforward method? -
I have a select menu and I want a query action when the user chooses an option value. I am using Django
<div class="row"> <div class="input-field col s2 offset-s1"> <select> <option value="" disabled selected>Options:</option> <option value="1">Display all</option> <option value="2">Sort by data</option> <option value="3">Sort by price</option> </select> </div> </div> How can I write the template code {% code %} and the views functions for making queries which depend by the select menu? -
Use HTML entities in django template
I want to use HTML entities in my Django template. I know that I can do something like this <th>0&ge;a&lt;10</th> and it will work correctly. But I send to my template list with that which looks like list_of_ranges = ['Name', 'Type', 'a<1', '5<a<10' .......] So in a template in for loop, I want to use &ge, &lt, and others for values that contain '>', '>=' and others. I tried to use it in the list before sending it to the template, but it's not working correctly. See below. list_of_ranges = ['Name', 'Type', 'a&lt;<1' .......] and in template fo like this {{list_of_ranges.2}} Result: a&lt;<1 Could you help, how can I resolve it? -
Can a django template call another template in Modal window?
My requirement is to a django template from another django template. the second template would open in a Modal window instead of taking me to a different page. Parent View : Basic Child View : Cancellation Can the child view template be kicked off through a modal? I am new to this so I need a sample code to achieve this. -
What is the best way to store chat Messages in Django for better performance
Currently, I am using default SQLite DB to store messages, as I am using channels... I update the Database at every send and receive a signal from WebSocket. but it would be too expensive when traffic will be large as at every send and receive I interact with Django ORM is there any other efficient way? class Room(models.Model): name = models.CharField(max_length=150) group = models.CharField(max_length=150,null=True) def __str__(self): return self.name class Message(models.Model): room = models.ForeignKey('Room',null=False,blank=False,on_delete=models.CASCADE) sender = models.ForeignKey(User,on_delete=models.CASCADE,null=True) message = models.TextField() def __str__(self): return self.message -
Django model class error when adding a new class into models
I have the following code: models.py from django.db import models class Title(models.Model): title_name = models.CharField(max_length=200) category = models.CharField(max_length= 30) class Tags(models.Model): tag1 = models.CharField(max_length=15) tag2 = models.CharField(max_length=15) tag3 = models.CharField(max_length=15) tag4 = models.CharField(max_length=15) class Videos: primo: str views.py from django.shortcuts import render, HttpResponse from django.http import HttpResponse from .models import Videos def home(request): vid = Videos() vid.primo = 'https://www.youtube.com/' return render(request, 'index.html', {'vid': vid}) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] When I run the server I get: RuntimeError: Model class home.models.Title doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Everything was working before adding class Videos() and just using: def home(request): return render(request, 'index.html') I don't understand what I should specify in the INSTALLED_APPS as I just added a new def to render a video URL inside my HTML. Why I get this error? Thanks!