Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to implement two user types (seller and customer or buyer) using django allauth like fiverr?
I am working on a web e-commerce project where there will be two types of user (seller, customer).I have been wondering how to implement the logic like fiverr seller and buyer. I have created a user account with two flags yet (is_seller, is_customer). class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=254, blank=True) customer = models.ForeignKey('Customer', on_delete=models.CASCADE) is_seller = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() I don't know if it is the good approach. what will be the best approach to this kind of scenario? kindly Someone guide me. Any help will be appreciated. -
heroku ps:scale web=1 on django gives errors
An am new to python and django trying to assign a dyno to my app on heruko using Django and i keep getting this "error: Missing required flag: -a, --app APP to run command". That's any time i type "heroku ps:scale web =1. I will really appreciate some help. Thanks -
Not able to return a query inside a get function in DRF. Please have a look and reply
I have to insert distance as an input parameter and work on this code. But I'm not able to return the query. When I run, the program is asking for distance. { "distance": [ "This field is required." ] } My code is as follows: from django.contrib.gis.geos import Point from django.contrib.gis.measure import D from Admin_Section.models import Distance class ServiceProviderList(generics.ListAPIView): serializer_class=ProfilecompletioneSerializer filterset_class=SnippetFilter filter_backends = [DjangoFilterBackend,SearchFilter,OrderingFilter] filterset_fields = ['fullname', 'category','departments','services'] search_fields = ['fullname', 'category__name','departments__dept_name','services__service_name'] def get_queryset(self,*args, **kwargs): pk=self.kwargs.get('pk') qs = CustomerProfile.objects.filter(user=pk) if qs.exists(): customer = qs.first() else: return qs.none() def get(self,request,*args, **kwargs): pk=self.kwargs.get('pk') customer = CustomerProfile.objects.get(user=pk) serializer = DistanceSerializer(data=request.data) serializer.is_valid(raise_exception=True) Dist = serializer.validated_data['distance'] print(Dist) rad=float(Dist) radius=rad/111 print(radius) query = ProfileCompletion.objects.filter(location__distance_lte=(customer.location,radius)) return query -
How to calculate mean value with respect to the month in DRF
I am trying to get the average with respect to the months of data in DRF. I have two problems here my values in the string so I need to convert first into double and then calculate it. I am not able to think any solution that's why posting the question without my solution what I have tried. My modal class is: class FeedDataValues(models.Model): sensor = models.ForeignKey( 'core.SensorDevice', on_delete=models.SET_NULL, null=True ) hardware_id = models.CharField(max_length=255) field1 = models.CharField(max_length=255, null=True) field2 = models.CharField(max_length=255, null=True) field3 = models.CharField(max_length=255, null=True) received_at = models.DateTimeField(null=True) My serializer class is: class MQTTFeedDataSerializer(serializers.ModelSerializer): class Meta: model = models.FeedDataValues fields = ('id','sensor','hardware_id','field1','field2','received_at',) And views is: class MQTTFeedDataListView(generics.ListAPIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated, permissions.IsAdminUser,) serializer_class = serializers.MQTTFeedDataSerializer queryset = models.FeedDataValues.objects.all() filter_backends = (DjangoFilterBackend, OrderingFilter,) filter_class = filters.MQTTFeedValuesFilter Any suggestion will be of great help. -
When to call gettoken, refresh token and verify token by user in jwt in DRF?
I have been using built in token authentication for my projects in Django rest framework. But now I am shifting to simple jwt. But I am confused on one thing. In Token Authentication user if logged in from front end returns a token, but in jwt documentation I have seen three requests as follows: urlpatterns = [ url(r'^auth-jwt/', obtain_jwt_token), url(r'^auth-jwt-refresh/', refresh_jwt_token), url(r'^auth-jwt-verify/', verify_jwt_token), ] I dont quite understand these requests. As a norman user, when a user visits a site he doest ask to get token, refresh token and verify token, he simply logs in and uses the features of the site. So, I am asking when these requests are made?? I hope I have explained well. -
How to add today's date to django templates
I researched how I could pass in a datetime object to my templates, but none of them seems to work. Here is the code for my view: class LeadListView(LoginRequiredMixin, generic.ListView): # some other code today_date = datetime.date.today() def get_context_data(self, **kwargs): context = super(LeadListView, self).get_context_data(**kwargs) context['today_date'] = self.today_date return context However, when I try to use the today_date in the template, it doesn't work. I am trying to use the today_date so that I might use it in an if statement to see if today's date is between two other datetime variables. Thanks a lot! -
Deleting the objects from Django table is not working
On a button click i want to delete an object from django database table. when i press delete button the desired object is gone. But when i refresh the page, the data is again loaded. How can i solve that error. I want to delete that object forever. Here is my code: models.py class activities(models.Model): name=models.TextField(max_length=60) description=models.TextField() date=models.TextField(max_length=60) list=models.TextField(max_length=60) Dates=models.DateField(max_length=60) root=models.ForeignKey(User ,on_delete=models.CASCADE,default='') def __str__(self): return self.name views.py: def dashboards(request): if request.method =='POST': user_id=request.POST.get('var') a = activities.objects.filter( id=user_id) a.delete() try: response = dashboard(request) except: return render(request,'contact.html') Any help is deeply appreciated. Thanks in advance -
Customized form for registration in django not working : meta tagged model shows no error, but not working
I'm trying to bootstrapify my customized registration page and fix my meta tag Things i've tried: I've altered the form in forms.py and added the extra fields When I remove the meta tag from my form, it has no effect at all, so I'm assuming something's wrong around there but I can't figure out what I'm using the inbuilt Django user model, and I've gone through many questions related to it without finding the solution. Any help would be highly appreciated !!! Note: An important thing is, even though I've mentioned a different order in the meta tag, it doesn't reflect the tag order in the html page Also my code shows me no errors Here's my forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class SignUpForm(UserCreationForm): email = forms.EmailField(widget = forms.EmailInput(attrs={'class' : 'form-control'}) ) first_name = forms.CharField(max_length=100, widget = forms.TextInput(attrs={'class': 'form- control'})) last_name = forms.CharField(max_length=100, widget = forms.TextInput(attrs={'class': 'form- control'})) class Meta: model = User fields = ('username', 'password1', 'password2', 'first_name', 'last_name', 'email') def __init__(self, *args, **kwargs): super(SignUpForm,self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] : 'form-control' self.fields['password1'].widget.attrs['class'] : 'form-control' self.fields['password2'].widget.attrs['class'] : 'form-control' Here's my views.py from django.shortcuts import render from django.views import generic from django.contrib.auth.forms import UserCreationForm from … -
HTTP 403 Forbidden in django-rest-framework
@api_view(['POST', 'GET']) def buyInstituteTutorialAPI(request,id): if request.session['type'] == "Student": user = User.objects.get(username=request.user) student = Student.objects.get(user=user) tutorial = TutorialInstitute.objects.get(id=id) if request.method == "GET": data = [] data['student'] = student.id data['tutorial'] = tutorial.id data['status'] = 1 if int(tutorial.Fees) == 0: buyData = BuyInstituteTutorialSerializer(data=data) if buyData.is_valid(): buyData.save() data['success'] = "Notes Bought Successfully!" else: data['error'] = "something error!" return redirect('view-tutorial-tutor-api') else: return Response(data) is that wrong method to send data in the serializer i'm logged with student but still shows this.... o/p: You do not have permission to perform this action -
Creating an object in django
I have just started learning Django and I am making a database using SQLite I have a python file called models.py and I am currently creating a py file for the objects called object. However I am having trouble creating objects in the database I have made. I think there is an issue with the object.py file because it is claiming that my FruitInfo sections have no objects. models.py from django.db import models from django.core.validators import MinLengthValidator, MaxValueValidator, MinValueValidator class FruitInfo(models.Model): id = models.IntegerField(primary_key=True, max_length=30, validators=[MinLengthValidator("5")]) name= models.CharField(max_length=30) origin = models.CharField(max_length=60) price = models.DecimalField(max_digits=4,null=False,decimal_places=2, validators=[MinValueValidator('200')]) def __str__(self): return self.origin + " " + self.name object.py from stinky.models import FruitInfo FruitInfo.objects.all() FruitInfor.objects.all().values() record = FruitInfo.objects.create(id = "A0001", name = "Pink Lady Apple", origin= "Washington State", price="$2.00/kg" ) record = FruitInfo.objects.create(id = "A0002", name = "Organic Bananana", origin = "Australia", price = "$4.50/kg") record = FruitInfo.objects.create(id = "A0003", name = "Orange", origin = "Indonesia", price = "$4/kg") record.save() -
How to resend a cognito invite
i need to resend cognito invite to users when the previously sent token expires in the documentation it's written like this --message-action (string) Set to "RESEND" to resend the invitation message to a user that already exists and reset the expiration limit on the user's account. Set to "SUPPRESS" to suppress sending the message. Only one value can be specified. Possible values: RESEND SUPPRESS -
Django Query select from where in
i need to write a query in django that creates a table with instructors name, department name, and total number of students taught. the part thats giving me trouble is the student count, i think i have the mysql query: select count (distinct ID) from takes where (course_id, sec_id, semester, year) in (select course_id, sec_id, semester, year from teaches where teaches.ID= Instructor.ID); or select count (distinct t1.ID) from takes as t1 inner join teaches as t2 on t1.course_id=t2.course_id and t1.sec_id=t2.sec_id and t1.semester=t2.semester and t1.year=t2.year where t2.ID= Instructor.ID my models are: class Takes(models.Model): id = models.ForeignKey(Student, models.DO_NOTHING, db_column='id', primary_key=True,) course = models.ForeignKey(Section, models.DO_NOTHING, related_name='+') sec = models.ForeignKey(Section, models.DO_NOTHING, related_name='+') semester = models.ForeignKey(Section, models.DO_NOTHING, db_column='semester', related_name='+') year = models.ForeignKey(Section, models.DO_NOTHING, db_column='year') grade = models.CharField(max_length=3, blank=True, null=True) class Meta: managed = False db_table = 'takes' unique_together = (('id', 'course', 'sec', 'semester', 'year'),) def __str__(self): return self.id class Teaches(models.Model): course = models.ForeignKey(Section, models.DO_NOTHING) sec = models.ForeignKey(Section, models.DO_NOTHING, related_name='+') semester = models.ForeignKey(Section, models.DO_NOTHING, db_column='semester', related_name='+') year = models.ForeignKey(Section, models.DO_NOTHING, db_column='year', related_name='+') id = models.ForeignKey(Instructor, models.DO_NOTHING, db_column='id', primary_key=True,) class Meta: managed = False db_table = 'teaches' unique_together = (('id', 'course', 'sec', 'semester', 'year'),) class Section(models.Model): course = models.ForeignKey(Course, models.DO_NOTHING) sec_id = models.CharField(max_length=8) semester = models.CharField(max_length=6) year … -
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS. HTTPS Websocket wss://
I am writing a website with 2 Django apps. A chat room and a Quiz website. used docker for the webSocket server: docker run -p 6379:6379 -d redis:5 I was using Channels and the app worked fine at https with (ws://) webSocket. But the client cant connect to the webSocket when i changed the link to wss://. Now i am trying to start the server using Daphne. But this has this error: daphne -p 8000 flippingClassroom.asgi:application django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. File tree: my-project chat templates index.html room.html admin.py consumers.py models.py routing.py urls.py views.py flippingClassroom asgi.py settings.py urls.py wsgi.py main ...another app chat/routing.py from django.urls import re_path from .consumers import ChatConsumer websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>[^/]+)/$', ChatConsumer.as_asgi()), ] chat/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<str:room_name>/', views.room, name='room'), ] chat/views.py from django.shortcuts import render # Create your views here. def index(request): return render(request, 'chat/index.html') def room(request, room_name): return render(request, 'chat/room.html', { 'room_name': room_name, 'username': request.user.username }) flippingClassroom/asgi.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import chat.routing os.environ.setdefault("DJANGO_SETTINGS_MODULE", … -
AttributeError: 'function' object has no attribute 'get_extra_actions' in function view
views.py @api_view(['GET', 'POST']) def poll(request): if request.method == "GET": question = Question.objects.all() serializer = QuestionSerializer(question, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == "POST": data = JsonParser.parse(request.POST) serializer = QuestionSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) api_urls.py from django.contrib import admin from django.urls import path, include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'poll', views.poll, basename='poll') urlpatterns = [ path('poll/', include(router.urls)), ] error File "C:\Users\azhar\.virtualenvs\Django_and_Rest-YRrszWnq\lib\site-packages\rest_framework\routers.py", line 152, in get_routes extra_actions = viewset.get_extra_actions() AttributeError: 'function' object has no attribute 'get_extra_actions' many solution available for how to use get_extra_actions in class View but I want to use it in poll function please help me out -
What is the best way to generate a primary key for a table from two strings?
Basically I'm trying to make my Django + PostgreSQL database perform better. Say I have a table with first_name, last_name, state, address. For whatever reason I want first_name and last_name together to make my primary key. Doesn't have to make sense, it's just an example. At first I used zlib.adler32() to generate a hash from the two strings and put it into a BigIntegerField and use that as my primary key, but I quickly discovered that the purpose of this function is totally different and I was getting collisions pretty quickly. Currently I'm using hashlib.md5() to generate a hash into a 32 character CharField and use it as my primary key: hashlib.md5(bytes(f'{first_name}{last_name}', encoding='utf-8')).digest().hex() However things slowed down a lot. I don't know if it's because of the md5 algorithm, or because of the table having a string for primary key instead of an integer. I know there is another option - unique_together value of the Meta class, but I've been trying to avoid any Django conveniences for performance reasons. How would you recommend to make a primary key? I'm looking for performance, doesn't need to be human readable. If BigInteger is much faster as a primary key, how do I … -
How to multiply parent model field with current model field in django?
class Items(models.Model): name = models.CharField(max_length=100, unique=True) price = models.IntegerField() image1 = models.ImageField(upload_to='images/', blank=True) image2 = models.ImageField(upload_to='images/', blank=True) image3 = models.ImageField(upload_to='images/', blank=True) def __str__(self): return self.name class Meta: verbose_name_plural = "Items" class Buy(models.Model): item = models.ForeignKey(Items, on_delete=models.CASCADE) quantity = models.IntegerField() total_price = models.IntegerField(default=0) @property def totalPrice(*args, **kwargs): self.total_price = self.quantity * self.item.price def __str__(self): return self.item.name class Meta: verbose_name_plural = "Buy" How to find the total price by mulitplying item price in first model with quantity in the second model....Please help -
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 1 with Heroku but not in local
When running my Django app on local environment, there are no issues. Using djstripe, I am able to, using stripe testing data, successfully create stripe checkout session and payment goes through. However, when trying this on Heroku I get a Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 1 preceded by POST 500 Internal Server error. second line (return fetch...) is causing the problem supposedly (in Heroku but not locally) var createCheckoutSession = function (priceId) { return fetch("/users/create-checkout-session/", { method: "POST", headers: { "Content-Type": "application/json", "X-CSRFToken": "******" }, body: JSON.stringify({ priceId: priceId }) }).then(function(result) { return result.json(); }); }; first line below also indicated as problem createCheckoutSession(basicannualPrice).then(function(data){ stripe.redirectToCheckout({sessionId: data.sessionId}); Console shows correct key for basicannualPrice and the url should work. What am I missing? Why would one environment work, and not another in this instance? -
How do I create a tree hierarchy in Django so that I can keep the requests to the backend to a minimum?
I'm working on a website where people can add exam questions. A question has the following properties(categories): Board (Edexcel, Cambridge) → Level (O, A - AS, A2) → Paper (subjects) → Year → Session (Aug, Jun, Jan) The board and level are fixed. There are only two boards and there are only four levels, these won't change. But, more papers and years can be added later, as needed. In the frontend, I'll create a tree structure. So, when someone clicks on one of the boards, it'll show the levels, click on one of the levels, it'll show the list of all subjects, click on one of the subjects, it'll show years and vice versa. Finally, it'll filter all the questions and only show those that met those filters. I haven't worked very long at the models yet. Do I need to create a separate model for each of them or do I just create models for those that will be updated through the dashboard later (paper, year, session) and hardcode the fixed ones (board, level)? This is how I am going about it: class Board(MPTTModel, models.Model): class Meta: verbose_name = _("Board") verbose_name_plural = _("Boards") class MPTTMeta: order_insertion_by = ['name'] name … -
DJango not finding static files, despite STATIC_URL and STATIC_ROOT set
I have just started learning DJango and am trying to use css file for my html template. As per the documentation, I have added the STATIC_URL and STATIC_ROOT to my settings.py file as follows: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') BASE_DIR is already set as follows: BASE_DIR = Path(__file__).resolve().parent.parent In the template, I am using the css file as follows {% load static %} <link rel="stylesheet" href="{% static 'style.css' %}"> and the style.css is present at location DJango_App/static, DJango_App being my project directory with the manage.py file. Still I am getting error "GET /static/style.css HTTP/1.1" 404 1653 DEBUG is set to True How do I resolve this? -
How to pass list of Django form field names to template?
I have a very basic form: class NavigationForm(forms.Form): NavSelection1 = forms.TextInput() In my view I want to pass a list to the template: form = NavigationForm() context['formfields'] = [i for i in form.fields] return render(request, "page.html", context) I am hoping to be able to use: {% for i in formfields %} {{i}} {% endfor %} But it returns nothing. {{formfields}} Alone returns an empty list [] I feel like I'm missing something simple but I'm stumped at the moment. Any help would be appreciated! -
Django - Custom values for inline list item field
After searching for a while, I can't seem to find any answer for this so I'm asking this question. What I want to is display some values based on a person's salary and a bracket. My models looks like this. class Employee salary = models.DecimalField class Benefit some_fields class EmployeeBenefit employee = models.ForeignKey benefit = models.ForeignKey class BenefitVersion benefit = models.ForeignKey class BenefitBracket benefit_version = models.ForeignKey from_salary = models.DecimalField to_salary = models.DecimalField the_fields_I_want_to_display As you can see it's quite deep, there would be a bunch of querying to do to get to the fields I want. I basically need to get the employee's salary(which is easy because this is gonna be inside EmployeeAdmin) then get the current benefit of the EmployeeBenefit list item, then based on the benefit and the employee's salary, get the bracket and then display some of it's fields on the inline. I want to display the the_fields_I_want_to_display on the admin.TabularInline for EmployeeBenefit inside my EmployeeAdmin. I was testing using a forms.ModelForm in the inline and modifying it's contents using get_form based on this answer but django is not calling get_form. I also previously tried using calculated_fields but it's not being rendered as well. -
DoesNotExist at /accounts/twitter/login/ SocialApp matching query does not exist
settings.py SITE_ID = 2 SOCIALACCOUNT_PROVIDERS = { 'twitter': { 'SCOPE': ['email'], 'AUTH_PARAMS': {'access_type': 'online'} } } twitter API Callback urls http://127.0.0.1:8000/accounts/twitter/login/callback/ Website Url https://twitter.com/_SANDEEP_AGR twitter api not accepting http://127.0.0.1:8000 as Website Url -
AJAX POST Data does not appear to be hitting Django Rest Framework API Endpoint
I am trying to build a feature with AJAX and DRF whereby a user can follow another user. However when I initiate it, the POSTed data does not appear to be hitting the DRF endpoint so I am getting no errors beyond: {user: ["This field is required."], following_user: ["This field is required."]} following_user: ["This field is required."] user: ["This field is required."] Here is my js function: const followUser = function(followedUser){ var pathArray = window.location.pathname.split('/'); var currentUser = pathArray[1]; console.log("Following" + " " + followedUser); $.ajax({ type: 'POST', url: '/api/userconnections/', data: { csrfmiddlewaretoken: document.querySelector('input[name="csrfmiddlewaretoken"]').value, 'current_user': currentUser, 'followed_user': followedUser }, success: function(data) { alert('Successfully Followed') } }); } Here is my serializer: class UserConnectionListSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField() following_user = serializers.StringRelatedField() class Meta: model = UserConnections fields = ['user','following_user'] class UserConnectionSerializer(serializers.ModelSerializer): class Meta: model = UserConnections fields = '__all__' And here is the views function: class UserConnectionsViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserConnectionListSerializer queryset = UserConnections.objects.all() def get_serializer_class(self): """IF this is a form post, use the basic serializer that deals with id (primary key) otherwise give the more sophisticated version that deals with actual username""" if self.request.method == 'POST': return serializers.UserConnectionSerializer return self.serializer_class def follow_user(request): if request.method == "POST": data = {'user': request.DATA.get('current_user'), 'following_user': request.DATA.get('followed_user')} … -
django many to many query
I'm attempting to create an application that would help me store old music. These are my models. class ArtistGenre(models.Model): genre_name = models.CharField('Genre', max_length=20) def __str__(self): return self.genre_name def get_absolute_url(self): return reverse('genre_detail', kwargs={'pk': self.pk}) class ArtistTrait(models.Model): trait_name = models.CharField('Trait', max_length=20) def __str__(self): return self.trait_name def get_absolute_url(self): return reverse('trait_detail', kwargs={'pk': self.pk}) class Artist(models.Model): stage_name = models.CharField('Stage Name', max_length=255) real_name = models.CharField('Birth Name', max_length=255, blank=True) artist_genre = models.ForeignKey(ArtistGenre, on_delete=models.CASCADE) artist_trait = models.ManyToManyField(ArtistTrait) def __str__(self): return self.stage_name def get_absolute_url(self): return reverse('profile_artist', kwargs={'pk': self.pk}) My hang-up is properly querying the ArtistGenre and ArtistTrait models in order to create clickable links that would list all artists in a Genre or with a particular Trait. Do I have to create Many To Many fields in the Trait and Genre models that link to the artists or is there a way for me to query the it currently? Thank You! -
face recognition using django, opencv, and flutter
Hi I am new in django and python, right now I would like to develop face recognition. There are so many resources to access live camera webcam to do face recognition, but here I would like to access live camera from flutter and connect it with the django as backend. Is it possible to do that ? So far, I have been following this article to do face recognition in live webcam https://www.mygreatlearning.com/blog/face-recognition/ and I still don't know how to make connection between django and flutter video_capture = cv2.VideoCapture(0) while True: ret, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(60, 60), flags=cv2.CASCADE_SCALE_IMAGE) rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) encodings = face_recognition.face_encodings(rgb) names = [] for encoding in encodings: matches = face_recognition.compare_faces(data["encodings"], encoding) name = "Unknown" if True in matches: matchedIdxs = [i for (i, b) in enumerate(matches) if b] counts = {} for i in matchedIdxs: name = data["names"][i] counts[name] = counts.get(name, 0) + 1 name = max(counts, key=counts.get) names.append(name) for ((x, y, w, h), name) in zip(faces, names): cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(frame, name, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2) cv2.imshow("Frame", frame) if cv2.waitKey(1) & …