Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error: django.db.utils.OperationalError: unrecognized token: ":"
When I try to save some Django model like for example this one: class UserProfile(models.Model): address = models.CharField(max_length=100, blank=True) payment_type = models.CharField(max_length=20, default="Undefined") total_no_of_products = models.IntegerField(default=0) total_paid = models.FloatField(default=0) ids = ArrayField(models.IntegerField(null=True, blank=True), default=list) user = models.OneToOneField(NewUser, on_delete=models.CASCADE, default=None) metadata = models.ManyToManyField(Metadata) def __str__(self): return f"{self.user.user_name}" I get in return following error: Error: django.db.utils.OperationalError: unrecognized token: ":" I try to figure out what cause this problem and I found that when I comment out this line ids = ArrayField(models.IntegerField(null=True, blank=True), default=list) problem disappear. Does anybody have idea why is this? Currently I'm using Django 5.0 with default sqlite3 db. Tnx! -
Extension for VS Code in Django projects where it is possible to view the page in real time
I need an extension for VS Code that simulates the browser on the VS Code screen itself. The problem is that I need to work on the page in real time, the way I work today, I need to change the html and css in my project, go to my browser, clear my browser's cache and only then load the page and check if you agree. I would like something similar to what the 'HTML play' extension does (this doesn't work because it doesn't load the static CSS and JS files as they are added to DJango). Any indications? I've already tried using: HTML Play Live Server -
sync_to_async decorator, async view in Django
I am trying to follow the video tutorial and try to understand async view and @sync_to_async decorator in django. I have this code: import time import asyncio from asgiref.sync import sync_to_async from django.http import HttpResponse from movies.models import Movie from stories.models import Story @sync_to_async def get_movies_async(): print('prepare to get the movies...') time.sleep(2) qs = Movie.objects.all() print('got all the movies') @sync_to_async def get_stories_async(): print('prepare to get the stories...') time.sleep(5) qs = Story.objects.all() print('got all the stories') async def main_view_async(request): start_time = time.time() await asyncio.gather(get_movies_async(), get_stories_async()) total = (time.time() - start_time) print("total: ", total) return HttpResponse('async!') But when I call main_view_async from my browser it still takes 7 seconds, not 5 seconds like in the video tutorial. The tutorial might be outdated (year 2020). Or perhaps I am doing something wrong? Can you please help? My output prepare to get the movies... got all the movies prepare to get the stories... got all the stories total: 7.0126471519470215 The tutorial terminal output prepare to get the movies... prepare to get the stories... got all the movies got all the stories total: 5.0126471519470215 -
Unable to use '?' to pass parameters when using pyodbc in Django for large query
Working on: Django framework pyodbc package (MSSQL Version 18) DS: Azure synapse I would like to know what is the best way to go about when trying to load a large number of parameters into the SQL query for Azure synapse. The scale I'm looking for is in millions. I can split the parameters into chunks of 2k which is the limit specified here: https://learn.microsoft.com/en-us/azure/synapse-analytics/sql-data-warehouse/sql-data-warehouse-service-capacity-limits#queries However, that would mean the number of queries would be too many. ~500 per million parameters. This isn't just for 1 type of parameter for e.g in where clause I may have 2 columns, each column with its own set of a million values which I would like to pass through the query params. What's the best way to about this? As a sidenote: I hadn't been able to get the queries working with '?' parameter holder, I had to use '%s' to fix this. Thanking in advance! -
drop down list is not getting populated in django, when data if fetched from databse
i want data from my database to display on the dropdown list , when user click on it, but its not happening my code is all correct , i am not able to find any mistakes please help me. this is my booking.html file <!-- booking.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Book a Court</title> <style> body { font-family: 'Arial', sans-serif; margin: 0; padding: 0; background-color: #f4f4f4; } header { text-align: center; background-color: #333; color: white; padding: 20px; } .container { max-width: 600px; margin: 50px auto; background-color: rgba(255, 255, 255, 0.8); padding: 20px; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } form { display: grid; gap: 15px; } label { font-weight: bold; } input, select { padding: 10px; border: 1px solid #ccc; border-radius: 5px; width: 100%; box-sizing: border-box; } button { background-color: #333; color: white; padding: 10px; border: none; border-radius: 5px; cursor: pointer; } </style> </head> <body> <header> <h1>Book Your Slot</h1> </header> <div class="container"> <form action="{% url 'book' %}" method="POST"> {% csrf_token %} <label for="id_name">Name:</label> <input type="text" id="id_name" name="name" required> <label for="id_mobile_number">Mobile Number:</label> <input type="text" id="id_mobile_number" name="mobile_number" required> <label for="id_court">Court:</label> <select id="id_court" name="court" required> {% for court in courts %} <option … -
Django QuestionForm in forms.py not Creating Instance in questions.html
I have a QuestionForm in forms.py meant to create instances of a Question model to appear in questions.html. However, when I submit the form, I am redirected back to ask_question.html without any new instance being created. Debugging Steps: 1. Admin Panel Creation I am able to create an instance of the Question model through the Django admin panel, which is currently the only instance displaying. 2. Frontend Submission I have tried creating an instance of the Question model using the front end, and no error message appears. However, no instance of the Question model appears in the questions.html template. 3. I inspected QuestionForm in forms.py it appears to be working as intended. class QuestionForm(forms.ModelForm): subject = forms.CharField(max_length=100, required=True, help_text='Enter a subject line for your question.') body = forms.CharField(widget=forms.Textarea, max_length=10000, required=True, help_text='Enter the main body of your question.') teacher_standard = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=[(1, 'High Expectations'), (2, 'Promoting Progress'), (3, 'Subject Knowledge'), (4, 'Planning'), (5, 'Differentiation'), (6, 'Assessment'), (7, 'Behaviour Management'), (8, 'Professionalism')], help_text='Select the standard(s) for which you are asking the question.' ) class Meta: model = Question fields = ['subject', 'body', 'teacher_standard'] 4. inspecting the Question model in models.py it appears to be working as intended. class Question(models.Model): title … -
Celery (with Redis) shows task as registered but nothing gets executed when called from python-django on EC2
I am totally lost on this one and hoping someone can help. I am using Celery-Redis to execute a long running task for my Django project. The setup works perfectly on my local Windows setup. I have been working on porting this to AWS EC2 for last few days with Nginx/Gunicorn running on Ubuntu. And at this point, everything seems to be working except the background task execution. I have installed Redis and Celery on the same EC2 instance where I have the webserver running. Both (Redis/Celery) start without issues and they acknowledge each other (connection is established). Celery even shows the registered tasks. However, whatever I do, the task does not get executed when the request is made from Django. I have put logging everywhere in the code and can see the task (executed with .delay()) being called but after that everything stops. The call never returns. No error messages either in Nginx or Gunicorn logs. Celery and Redis-server both are running on the terminal with logging on so that I can see any messages. No messages in any of them as if they are not called at all. I have also tried to execute the task without .delay … -
store.models.variation_price.product.RelatedObjectDoesNotExist: variation_price has no product
I am working on a Django project which has models shown below. I'm trying to filter filter_horizontal field in admin.py. class VariationManager(models.Manager): def color(self): return super(VariationManager,self).filter(variation_category='color', is_active=True) def sizes(self): return super(VariationManager, self).filter(variation_category='size', is_active=True) variation_category_choice = ( ('color', 'color'), ('size', 'size'), ) class Variation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) variation_category = models.CharField(max_length=100, choices=variation_category_choice) variation_value = models.CharField(max_length=100) objects = VariationManager() class variation_price(models.Model): price = models.IntegerField() product = models.ForeignKey(Product, on_delete=models.CASCADE) variations = models.ManyToManyField(Variation, blank=True) is_active = models.BooleanField(default=True) In admin.py of project, I have: class variation_priceForm(forms.ModelForm): class Meta: model = variation_price fields = ['price','product','variations','is_active'] def __init__(self, *args, **kwargs): super(variation_priceForm, self).__init__(*args, **kwargs) self.fields['variations'].queryset = Variation.objects.filter(product=self.instance.product) @admin.register(variation_price) class variation_priceAdmin(admin.ModelAdmin): form = variation_priceForm filter_horizontal = ('variations',) list_display = ('get_variations', 'price', 'stock','id','is_active') list_editable = ('is_active',) I'm getting an error saying: store.models.variation_price.product.RelatedObjectDoesNotExist: variation_price has no product Thanks. Any help is appreciated -
Beginner trying to run Django project using Dockerfile
I am new to Docker. I am trying to run a basic project that I have made in Django. My Dockerfile is: FROM python:3 COPY members /associate/ WORKDIR /associate RUN pip install Django WORKDIR /associate/forening EXPOSE 8000 CMD ["python", "manage.py", "runserver", "8000"] My django project is in a folder called members. What I am trying to do above is to install django to the virtual environment of the django project which has been copied to the folder associate. But I can’t find the server http://127.0.0.1:8000/ which exists on my computer locally when i run the django project. Also, where are my docker images and containers stored? When I run docker info it says that docker root directory is var/lib/docker but no such directory exists. Right now I am running docker images from the graphical user interface in docker desktop -
Multiple static files within separate Django templates (using block.super with multiple included files)
I don't necessarily have a problem, but I'm unsure if this is good practice. I'm working on a Django project. I've set up a base.html, navbar.html and sidenav.html and made separate .css and .js files for each. I have then included those static files separately in each .html file within separate blocks. Here's partial code, to explain what I've done: base.html {% load static %} ... <head> ... <!-- CSS import --> {% block css_import %} <link rel="stylesheet" href="{% static 'path/to/base.css' %}" /> {{ block.super }} {% endblock %} ... </head> <body> {% block navbar %} {% include 'navbar.html' %} {% endblock %} ... {% block sidenav %} {% include 'sidenav.html' %} {% endblock %} ... <!-- JS import --> {% block js_import %} {{ block.super }} {% endblock %} </body> ... navbar.html {% load static %} {% block css_import %} <link rel="stylesheet" href="{% static 'path/to/navbar.css' %}" /> {% endblock %} <!-- Navbar content --> {% block js_import %} <script src="{% static 'path/to/navbar.js' %}"></script> {% endblock %} sidenav.html looks structurally basically the same, also having css_import and a js_import blocks. Now, I can say that everything seems to work just fine as apparently block.super takes blocks from both included .html … -
Slow performance when order by field in foreign key
When a queryset is sorted by a field in a related model performance decreases drastically. I use mysql. For example, I have two models: class Event(models.Model): idEvent = models.BigAutoField(primary_key=True) created_at = models.DateTimeField(db_index=True, verbose_name=_('date')) processed_at = models.DateTimeField(auto_now_add=True, verbose_name=_('processed')) data = models.TextField() class Meta: ordering = ["-created_at"] # [1154519 rows] class AccessHistory(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE, blank=True, null=True) result = models.TextField(verbose_name=_('result')) # [1130603 rows] If I do AccessHistory.objects.all().select_related('event').order_by('-event__created_at') the query delays over 5s, if I swap select_related with prefetch_related I get the same delay. When I do the query without ordering it responds in the expected time (<1s) -- AccessHistory.objects.all().select_related('event').order_by('-event__created_at') SELECT `history_accesshistory`.`id`, `history_accesshistory`.`event_id`, `history_accesshistory`.`result`, `history_event`.`idEvent`, `history_event`.`created_at`, `history_event`.`processed_at`, `history_event`.`data` FROM `history_accesshistory` LEFT OUTER JOIN `history_event` ON (`history_accesshistory`.`event_id` = `history_event`.`idEvent`) ORDER BY `history_event`.`created_at` DESC -- AccessHistory.objects.all().prefetch_related('event').order_by('-event__created_at') SELECT `history_accesshistory`.`id`, `history_accesshistory`.`event_id`, `history_accesshistory`.`result` FROM `history_accesshistory` LEFT OUTER JOIN `history_event` ON (`history_accesshistory`.`event_id` = `history_event`.`idEvent`) ORDER BY `history_event`.`created_at` DESC I tried with select_related, prefetch_related, indexing created_at field in Event model and setting a default order in Event model. Nothing of this improves the response time. How I can optimize this without moving/copying created_at field to AccessHistory model? -
Processing Model fields during the save process - Django
In my application, the user modifies their profile data and the data is POSTed to ProfileUpdateView upon save. The UI allows the user to modify each of their attributes individually (via AJAX calls) and hence I created multiple Form classes to represent this ability. If I had created a single Form class, the is_valid method would have failed or I would have to write complex validation logic to determine which field was being edited Some fields require pre and/or post-processing during the save operation. I was unable to find any examples on how to best do the same elegantly. So created a dictionary that maps modified field to pre-processing, form class and post-processing methods (instead of nested if-then-else within the post method). Then the view dynamically determines which to apply based on the input in the POST My approach considerations were Focusing, above all else, on code readability and maintainability Keeping custom logic as minimal as possible but this is hard when you are writing a custom application Questions to the community I would truly appreciate your constructive criticism of my design / approach. I am sure there are more elegant ways to accomplish what I am doing and I … -
psql version does not change to 12 even after upgrade
I have acquired an image of postgre sql and i have imported data into the a table my_spo_stats in database music. I intended to build a webpage with Django with this being my database, so i started in this container building Django projects. However, when i ran python3 manage.py makemigrations, I got the following error: raise NotSupportedError( django.db.utils.NotSupportedError: PostgreSQL 12 or later is required (found 11.9). but i did pull the image specifying the version to be 12. Regardless, i tried to upgrade my psql . i did sudo apt-get update. sudo apt-get install postgresql-12 postgresql-server-dev-12, and (in case of any need for closer examination here) the output was invoke-rc.d: could not determine current runlevel invoke-rc.d: policy-rc.d denied execution of start. Setting up libsensors-config (1:3.6.0-2ubuntu1.1) ... Setting up libllvm10:amd64 (1:10.0.0-4ubuntu1) ... Setting up postgresql-client-12 (12.17-0ubuntu0.20.04.1) ... update-alternatives: using /usr/share/postgresql/12/man/man1/psql.1.gz to provide /usr/share/man/man1/psql.1.gz (psql.1.gz) in auto mode Setting up ssl-cert (1.0.39) ... debconf: unable to initialize frontend: Dialog debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 76.) debconf: falling back to frontend: Readline Setting up libclang1-10 (1:10.0.0-4ubuntu1) ... Setting up postgresql-common (214ubuntu0.1) ... debconf: unable to initialize frontend: Dialog debconf: (No … -
Django: Custom forms for each record
I am making a web app with the model below. I would like to make a list of Meals with checkboxes displayed depending on whether each meal offers takeaway, eat_in or both and sign them up as a Participant with their choice of takeaway, eat_in or both. from django.db import models from django.utils.timezone import localtime from django.conf import settings from django.db import models # Create your models here. class Meal(models.Model): meal_time = models.DateTimeField("Tid/Dato") meal_description = models.CharField(verbose_name="Beskrivelse af måltid", max_length=300) meal_deadline = models.DateTimeField(verbose_name="Tilmeldingsfrist") meal_price_pp = models.DecimalField(verbose_name="Pris per person", decimal_places=2, max_digits=5) meal_price_tt = models.DecimalField(verbose_name="Pris i alt", decimal_places=2, max_digits=5) meal_resp = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) meal_offer_takeaway = models.BooleanField(verbose_name="Tilbyd takeway", default=False) meal_offer_eat_in = models.BooleanField(verbose_name="Tilbyd spisning i netværket", default=False) # meal_timezone = models.CharField(verbose_name="Tidszone", default='Europe/Copenhagen', max_length=50) def __str__(self): return (f"{self.meal_description} Dato:" f" {localtime(self.meal_time).date().strftime("%d/%m/%Y")} " f"{localtime(self.meal_time).strftime("%H:%M")} Pris: {self.meal_price_pp}") def weekday(self): weekdays = ["Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag", "Søndag"] index = self.meal_time.date().weekday() return weekdays[index] def resp_name(self): return self.meal_resp.name class Participant(models.Model): list_user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="Bruger", on_delete=models.CASCADE) list_meal = models.ForeignKey(Meal, verbose_name="Måltid", on_delete=models.CASCADE) list_takeaway = models.BooleanField(verbose_name="Tilmeld takeaway", default=False) list_eat_in = models.BooleanField(verbose_name="Tilmeld spisning i netværket", default=False) list_registration_time = models.DateTimeField(verbose_name="Date/time registered") payment_due = models.DateField(verbose_name="Betales senest") payment_status = models.BooleanField(verbose_name="Er betalt", default=False) def registered_on_time(self): meal_record = self.list_meal return self.list_registration_time <= meal_record.meal_deadline def __str__(self): return f"Bruger: {self.list_user} … -
How I can throttle only the POST method in this views
class ExampleView(APIView): throttle_classes = [UserRateThrottle] def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) def post(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) I want to throttle only the post method view not the get. I have declared two views POST and GET and I want only to implement throttling for my POST view -
Custom Adapter inheriting from DefaultSocialAccountAdapter in django-allAuth throwing error
I am using django-allauth to login with Steam in my Django application. I want that when a new user signs up, the user's steam id is also stored in the database. I want to extend the DefaultSocialAccountAdapter and use a custom adapter. Here is my code from allauth.socialaccount.adapter import DefaultSocialAccountAdapter import logging logger = logging.getLogger(__name__) class CustomAccountAdapter(DefaultSocialAccountAdapter): def save_user(self, request, user, form, commit=True): user = super().save_user(request, user, form, commit=False) social_account = user.socialaccount_set.filter(provider='steam').first() if social_account: user.steam_id = social_account.uid if commit: user.save() return user When I use this adapter by setting the SOCIALACCOUNT_ADAPTER in my settings.py file, it throws an error stating DefaultSocialAccountAdapter.new_user() missing 1 required positional argument: 'sociallogin' I also tried to over-ride the new_user method but still got the same error. I tried this: def new_user(self, request): user = super().new_user(request) user.steam_id = sociallogin.account.uid return user But the error remains the same. It shows the error at /usr/local/lib/python3.10/site-packages/allauth/socialaccount/adapter.py, line 71, in new_user """ pass def new_user(self, request, sociallogin): """ Instantiates a new User instance. """ return get_account_adapter().new_user(request) <--- error on this line def save_user(self, request, sociallogin, form=None): """ Saves a newly signed up social login. In case of auto-signup, the signup form is not available. """ I went ahead and looked … -
ModuleNotFoundError: No module named 'school.message_test'
I'm encountering a ModuleNotFoundError when trying to import a module in my Django project. Here's the code snippet: import os import django from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from django.core.asgi import get_asgi_application from school.message_test.routing import websocket_urlpatterns os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'school.settings') django.setup() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ), }) specifically on this line: from school.message_test.routing import websocket_urlpatterns I've double-checked that all the paths are correct, and the file is in the right directory. What could be causing this issue, and how can I resolve it? to run the project I used this command: daphne -p 8000 school.asgi:application I'll try to use a relative path which naturally won't work. I also tried using it for the top level, that is from ..message_test.routing import websocket_urlpatterns but it doesn't work because asgi doesn't allow it the path is absolutely correct, what can you tell me? photo of the full project path -
Django: Convert IntegerField to ForeignKey
I have a database with this django model: class System(models.Model): system_id = models.IntegerField(primary_key=True) constellation_id = models.IntegerField() It already has some data, and EVERY row of the table has constellation_id. And now I created a new table with data: class Constellation(models.Model): constellation_id = models.IntegerField(primary_key=True) Is it possible to refactor constellation_id of System model from IntegerField into ForeignKey? All of the constellation_ids in System table exist in Constellation table. -
Image is not displaying in Django from static
The following is the only code where I mention the image: Inside the HTML and CSS file: <button type="submit" class="task-item-button"> <img src="{% static 'x.svg' %}" alt="Close icon"> </button> .task-item-button { position: absolute; top: 10px; /* Adjust the top position */ right: 10px; /* Adjust the right position */ width: 20px; height: 20px; color: red; padding: 0; border: none; background: none; border-radius: 8px; cursor: pointer; } .task-item-button img { width: 20px; /* Adjust the width of the image as needed */ height: 20px; /* Adjust the height of the image as needed */ } and I do have {% load static %} at the top. Apart from that I have no other mentions of the images anywhere. The structure of static looks like: Thanks for any help. -
Why can't I activate virualenv on Mac?
I'm was working on a project few months earlier that I hadn't modified in the las 3 months. During this period I changed my Macbook and transferred everything with Time Machine. My other projects that don't using virtualenv works fine but in case of this project I am not able to activate the virtualenv. Structure: coachregiszter --bin --include --lib --mcr (this is my project folder where manage.py is) --pyenv.cfg If I try: source bin/acivate I get this error message: source bin/activate Script started, output file is started Script: on: No such file or directory Script done, output file is started bin/activate:2: bad pattern: ^[[1m^[[7m%^[[27m^[[1m^[[0m What is the problem? -
How to convert string filed to list field in serializer
I have a simple django model models.py file: from django.db import models class MyModel(models.Model): my_field = models.CharField(max_length=20) def __str__(self): return self.my_field serializers.py file from rest_framework import serializers from .models import MyModel class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' Using generic view I list all of items views.py from rest_framework import generics from .serializers import MySerializer from .models import MyModel class TestView(generics.ListAPIView): serializer_class = MySerializer queryset = MyModel.objects.all() urls.py from django.urls import path from . import views urlpatterns = [ path('test\', views.Test.as_view()), ] And I got following json output: [ { "id":1, "my_field":"a,b,c" }, { "id":2, "my_field":"a" }, { "id":3, "my_field":"b,c" } ] Now I want to convert my_filed values from string to comma-separated list, expected output: [ { "id":1, "my_field":["a", "b", "c"] }, { "id":2, "my_field": ["a"] }, { "id":3, "my_field":["b", "c"] } ] I tried to modify MySerializer as below: serializers.py from rest_framework import serializers from .models import MyModel class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' def __init__(self, *args, **kwargs): super(MySerializer, self).__init__(*args, **kwargs) return self.fields['my_field'].split(',') but I got AttributeError: CharField object has no attribute 'split'. Do you have any ideas how to get expected output? Any hints are appreciated! -
Asynchronous processing when using Celery in a Django application (Heroku)
I am developing an application that uses the Whisper API to convert uploaded audio files into text. I am trying to use Celery for asynchronous processing, but I can't seem to reference the media file properly. I get a "FileNotFoundError: [Errno 2] No such file or directory: '/app/media/audio/xxx.mp3'" error. Before the asynchronous processing, I was able to reference the file with no problem. What should we do in such a case? ・setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') ・views.py upload_path = os.path.join(settings.MEDIA_ROOT, "audio") audio_file_path = os.path.join(upload_path, file) convert_text.delay(audio_file_path) ・tasks.py @shared_task def convert_text(audio_file_path): openai.api_key = "xxxxxxxxxxx" audio_file= open(audio_file_path, "rb") transcript = openai.Audio.transcribe("whisper-1", audio_file) text_data = transcript["text"] -
React 'style' conflict with Django template(?)
So I'm using python django as well as inline babel script (React). Now my problem is I think that React's style style={{ height : '100px' }} conflicts with Django templates. I tried using djangos verbatim tag but still no luck. -
Django Mail Template Rendering With render_to_string
I am trying to send mail with django and I can send but when I am sending the mail, it contains <body> tags or <div> tags, I can not customize the mail template. I am using this code in my views.py template = render_to_string('mailapp2/email.html', { 'name':request.user.username, 'date':date, 'city':city, }) email = EmailMessage( 'Meeting Notification', template, settings.EMAIL_HOST_USER, [request.user.email], ) email.fail_silently=False email.send() How can I solve this, thank you from now :) I have tried using css but I can not use <div> tags for using id or class -
How can I get a batch of frames from consumers.py?
Currently, I am working on a computer vision project that involves object detection and real-time frame streaming using opencv and django. To accomplish this, I am utilizing django-channels. However, I have encountered a new challenge where I need to perform video classification. This requires sending a batch of frames to the model. Can you provide any guidance on how to approach this issue? I added a button on the front-end. What I expected was to obtain a single timestamp from the back-end consumers.py. What I got was the timestamp of the start frame till the timestamp of the frame where the button was clicked. Here is an example image of it In the consumers.py file, I'm utilizing the OpenCV library to iterate through the frames, and then I'm transmitting that data to the websocket client. Here is an example of the code (I have also provided the comments for better understanding). # Import the 'cv2' module, which is the OpenCV library for computer vision tasks. import cv2 # Import the 'json' module for working with JSON data. import json # Import the 'asyncio' module for asynchronous programming support. import asyncio # Import the 'datetime' module for working with date and …