Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django mptt change selected value of TreeNodeChoiceField
I'm trying to use Django MPTT to display a list of nested categories in a select form using TreeNodeChoiceField forms.py class CategoryForm(forms.ModelForm): class Meta: model = Category fields = [] category = TreeNodeChoiceField(queryset=Category.objects.all(), label='') When I render the form in the template, I get the following select As you can see the selected option contains dashes and I haven't figured out how to change it. It would be nice if I can change it to a more meaningful name like "Category" -
Create sub-folders inside app Templates in Django
I've created a sub-folder name Housekeeping inside Properties in my templates folder as can be seen in the picture below. I've done it to better organize things. Problem The situation here is that my UpdateView looks for the template inside the app folder Properties and not inside Housekeeping. This ends up showing me this error: TemplateDoesNotExist at /properties/1/housekeeping/housekeeper/edit properties/propertyhousekeeper_update_form.html Which in fact makes sense.. If I move the file to inside the properties folder it works fine. For reference: #views.py class HousekeeperUpdateView(UpdateView): # login_url = '/login/' redirect_field_name = 'properties/housekeeping/housekeeping.html' template_name_suffix = '_update_form' form_class = HousekeeperAddForm model = PropertyHousekeeper Is there a way to do this? Or can it be done? -
Page not found (404) URLconf
when i run the server this show up Page not found (404) Using the URLconf defined in notes.urls, Django tried these URL patterns, in this order: admin/ notes/ The empty path didn't match any of these notes urls.py from django.contrib import admin from django.urls import include , path urlpatterns = [ path('admin/',admin.site.urls), path('notes/', include('notes_app.urls')) ] notes_app urls.py from django.contrib import admin from django.urls import include , path urlpatterns = [ path('admin/',admin.site.urls), path('notes/', include('notes_app.urls')) ] view from django.shortcuts import render from django.http import HttpResponse from .models import Note # Create your views here. ## show all notes def all_notes(request): # return HttpResponse('<h1> Welcome in Django Abdulrahman </h1>' , {}) all_notes = Note.objects.all() context = { 'all_notes' : all_notes } return HttpResponse (request , 'all_notes.html' , context) ## show one note def detail(request , id): note - Note.objects.get(id=id) context = { 'note' : Note } return render(request,'note_detail.html' , context) image -
GET http://localhost:8000/project:slug
Running localhost:8000/random-string returns "page not found" I believe my code is all running smoothly because if it wasn't I don't think when I run manage.py runserver it will load my local host successfully. There's another post which I believe the issue is similar and pointed to something in the codes environment not being set up correctly. I've tried to follow the answer from other issue but that didn't quite work for me. To provide more context this is how the error message looks like in my CMD: financio>manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 12, 2019 - 17:37:26 Django version 2.2.5, using settings 'financio.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: /random-string [12/Sep/2019 17:37:30] "GET /random-string HTTP/1.1" 404 2327 Within my budget folder which is nested in the parent folder I have my urls.py: from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.project_list, name='list'), path('<slug:project:slug>', views.project_detail, name='detail') ] When I run localhost:8000/random-string it is meant to load the following page project-detail.html: {% extends 'budget/base.html' %} {% block content %} <div class="container"> <section class="section section-stats"> <div … -
add to wishlist function didn't work properly as i wanted
This add_to_wishlist return two messages and eventually get_or_create act like this. But i want if an item added first time it shows "added" and next time "already added" but it return both when i click to the button. How i checked or make a query that it return me it added firstime. i used get_or_create method. As far as i know when there is no existence of an item it will create one and if already exits it will get or override the item. I have try it in add_to_cart and it worked perfectly. here is the model class Wishlist(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) wished_item = models.ForeignKey(Item,on_delete=models.CASCADE) slug = models.CharField(max_length=30,null=True,blank=True) added_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.wished_item.title here is the function @login_required def add_to_wishlist(request,slug): item = get_object_or_404(Item,slug=slug) wished_item,created = Wishlist.objects.get_or_create(wished_item=item, slug = item.slug, user = request.user, ) messages.info(request,'The item was added to your wishlist') wish_list_qs = Wishlist.objects.filter(user = request.user, slug=item.slug) if wish_list_qs.exists(): messages.info(request,'The item was already in your wishlist') return redirect('core:product_detail',slug=slug) it shows both messages .... but I want one according to the action either added the first time or added again The item was added to your wishlist The item was already in your wishlist -
how to save data of form wizard data in database in django
i want make add profile page in multiple steps and of that page when user submits their form and then this data is saved to database of django admin ## forms.py ## class FormStepOne(forms.Form): firstname = forms.CharField(max_length=100) lastname = forms.CharField(max_length=100) phone = forms. CharField(max_length=100) email = forms.EmailField() class Meta: model = FormStepOne fields = ['firstname', 'lastname', 'phone', 'email'] class FormStepTwo(forms.Form): skills = forms.CharField(max_length=100) salary = forms.CharField(max_length=100) job_description = forms.CharField(widget=forms.Textarea) class Meta: model = FormStepTwo fields= ['skills','salary','job_description'] ## views.py ## class FormWizardView(SessionWizardView): # # def done(self,request, form_list, **kwargs): # return render(self.request, 'accounts/online/profile.html', { # 'form_data': [form.cleaned_data for form in form_list], # }) # # if request.method == 'POST': # form = FormStepOne(request.POST) # if form.is_valid(): # form.save() # firstname = form.cleaned_data.get('firstname') # lastname=form.cleaned_data.get('last_name') # # messages.success(request, f'You successfully registered!') # return redirect('online_dashboard') # context={'form:from'} # else: # form = () # return render(request, 'accounts/online/firststep.html', {'form': form, 'title': ' Sign Up'}) this is my first time on stackoverflow so help me out of this problem and thanks in advance -
How to to forbid access my site from ip address+port using nginx?
I have a django app with gunicorn running on port 2333.In nginx.conf I set server { listen 80; server_name mydomain.com; location / { proxy_cache my_cache; proxy_set_header REMOTE-HOST $remote_addr; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:2333; expires 30d; } now I can view my django app on address http://ipaddress:2333 and mydomain.com but I don't want users to view my site by http://ipaddress:2333 .How to allow nginx only use mydomain.com to access my site. I have tried to use "server default".It not worked. server { listen 2333 default; server_name _; return 500; } -
R Reverse for 'results' not found. 'results' is not a valid view function or pattern name
I am learning django framework and i am getting an error " Reverse for 'results' not found. 'results' is not a valid view function or pattern name." I am including my code here. "results.py" {% extends "polls/base.html" %} {% block main_content %} <h1>{{question.question_text}}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{choice.choice_text}} -- {{choice.votes}} vote{{choice.votes|pluralize}}</li> {% endfor %} </ul> <a href="{% url 'polls:details' question.id }">Vote again</a> {% endblock%} "views.py" from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse,HttpResponseRedirect # from django.core.urlresolvers import reverse from .models import Question from django.urls import reverse def results(request,question_id): question=get_object_or_404(Question,pk=question_id) return render(request,"polls/results.html",{"question":question}) def vote(request,question_id): question=get_object_or_404(Question,pk=question_id) try: selected_choice=question.choice_set.get(pk=request.POST['choice']) except: return render(request,"polls/details.html",{'question':question,"error_message":"Please select a choice"}) else: selected_choice.votes+=1 selected_choice.save() return HttpResponseRedirect(reverse("polls:results",args=(question.id,))) -
Only last form in the inlineformset_factory is saved
I am getting only the last form using inlineformset_factory. Here is is codes. I have tried with different answers but couldn't find my own bug. Is it something with js script or anything else? Please help me to find it. model.py from django.db import models # Create your models here. class DAILY_REPORT(models.Model): report_date = models.DateField() # AutoNow = True sets the time when the object created district = models.CharField(max_length=100) def __str__(self): return f"{self.district}" class GURUTTOPUNNO_NIYOMITO_MAMLA(models.Model): daily_report = models.ForeignKey(DAILY_REPORT, on_delete=models.CASCADE) mamlar_number = models.DecimalField(max_digits=10, decimal_places=2, null=True) # ejaharer_description = models.TextField() # ejaharer_ashami_number = models.DecimalField(max_digits=10, decimal_places=2) # greptarer_number_ejahar = models.DecimalField(max_digits=10, decimal_places=2) # greptarer_number_shondhigdho = models.DecimalField(max_digits=10, decimal_places=2) # uddhar = models.DecimalField(max_digits=10, decimal_places=2) # comment = models.DecimalField(max_digits=10, decimal_places=2) class DOINIK_GREPTAR(models.Model): daily_report = models.ForeignKey(DAILY_REPORT, on_delete=models.CASCADE) da_b_dhara_290 = models.DecimalField(max_digits=10, decimal_places=2) forms.py from django import forms from django.forms import modelformset_factory, ModelForm, inlineformset_factory from .models import DAILY_REPORT, DOINIK_GREPTAR, GURUTTOPUNNO_NIYOMITO_MAMLA class DAILY_REPORT_FORM(ModelForm): district = forms.CharField(label='জেলার নাম') #widget=forms.Textarea(attrs={"placeholder":"জেলার নাম"})) report_date = forms.DateField() class Meta: model = DAILY_REPORT fields = [ 'district', 'report_date' ] class DOINIK_GREPTAR_FORM(ModelForm): class Meta: model = DOINIK_GREPTAR fields = '__all__' class GURUTTOPUNNO_NIYOMITO_MAMLA_FORM(ModelForm): class Meta: model = GURUTTOPUNNO_NIYOMITO_MAMLA exclude = ('daily_report',) GURUTTOPUNNO_MAMLA_FORMSET = modelformset_factory(GURUTTOPUNNO_NIYOMITO_MAMLA, form=GURUTTOPUNNO_NIYOMITO_MAMLA_FORM, exclude=('daily_report',),extra=1) # class WeeklyProgressReportForm(forms.ModelForm): # class Meta: # model = WeeklyProgressReport # fields = … -
Use a For loop to save fields from a database into a numpy array
I have a database that is filled with values from a numpy array that gets its data from the face_recognition image. The fields in my database are as follows: f1: (double) f2: (double) ... f128: (double) i want to retrive this points and save them into a numpy array, to fill this numpy array im using a for loop: for x in range(0, 129): result = face.f1 known_image = np.append(known_image, result) What i need is to be able to change that face.f1 for face.f2 in the second loop and so on. Note that f1,f2... are values already stored in the database. -
How to achieve below objective.?
I am using celery with Django. Redis is my broker. I am serving my Django app via Apache and WSGI. I am running celery in supervisor mode. I am starting up a celery task named run_forever from wsgi.py file of my Django project. My intention was to start a celery task when Django starts up and run it forever in the background (I don't know if it is the right way to achieve the same. I searched it but couldn't find appropriate implementation. If you have any better idea, kindly share). It is working as expected. Now due to certain issue, I have added maximum-requests-250 parameter in the virtual host of apache. By doing so when it gets 250 requests it restarts the WSGI process. So when every time it restarts a celery task 'run_forever' is created and run in the background. Eventually, when the server gets 1000 requests WSGI process would have restarted 4 times and I end in having 4 copies of 'run_forever' task. I only want to have one copy of the task to run at any point in time. So I would like to kill all the currently running 'run_forever' task every time the Django starts. … -
Auto scroll iframe window during StreamingHttpresponse
I've got a StreamingHttpResponse function that I am running inside of a iframe child the code for the iframe is below. The iframe, and function is working properly but the function sometimes returns a very long output and you either need to hold down "page down" or constantly use mouse wheel to see the latest and greatest output. I'd like for it to automatically scroll when html/text is received in the browser. I believe I might be restricted by an html or css solution? I'm not sure if jQuery or Javascript of some sort will process properly in the StreamingHttpResponse which is why I included Django as a related framework. I've tried a div style overflow auto scroll solution without success. Here's the iframe code: <iframe src="{% url 'landingpage' %}" frameBorder="0" name="botframe3" scrolling="yes" style="position: absolute; height: 70%; width: 100%;"></iframe> Here's the StreamingHttpResponse call: @condition(etag_func=None) def stageDevice(request, cmd, pk): pullID = Pull.objects.filter(pk=pk)[0] pullIDq = Pull.objects.filter(pk=pk) emailListqc = EmailList.objects.filter(ccqc='yes') emailListstg = EmailList.objects.filter(ccstg='yes') reqUser = User.objects.get(username=request.user.username) return StreamingHttpResponse(runSetup(pullID, pullIDq, reqUser), content_type='text/html') Here's the runSetup function: def runSetup(pullID, pullIDq, reqUser): yield "<html><head><title>Setup Phase</title>\n" yield "<link rel='stylesheet' href='/static/css/base.css'>\n" yield "<link rel='stylesheet' href='/static/css/style.css'>\n" yield "<link rel='stylesheet' href='https://bootswatch.com/4/cyborg/bootstrap.css'></head>\n" yield "<div>Attempting to setup for pull ID {0} - … -
returning email = None when updating / creating a new user from the admin panel
I just created a custom User Model and a custom User Manager. Now, I want to be able to update / create users from the django admin panel. It works perfectly fine from the django ORM, but when it comes to the admin panel, the USERNAME_FIELD ( which is set to email ) returns None after every time I'm trying to update or create a new user. Here is my Model and my Manager : class UserManager(BaseUserManager): #custom create_user method def create_user(self, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email = self.normalize_email(email) ) print(email) user.set_password(password) user.save(using=self._db) print(user) return user #Custom create_super_user method def create_superuser(self, email, password=None): user = self.create_user( email = email, password = password ) user.admin = True user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class User(AbstractBaseUser): #setting up Choices for interest, Must add other fields ... #interests = MultiSelectField( # max_length = 2, # choices = INTERESTS_CHOICES #) #Setting up a Ranking System email = models.EmailField( max_length=50, unique=True, blank=False, null=False ) username = models.CharField( max_length=25, unique=True, null=True, blank=True ) date_joined = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=70) birth_date = models.DateField(null=True, blank=True) reputation = models.PositiveIntegerField(default=0) is_active = models.BooleanField(default=True) … -
Django: extend QuerySet with a default filter
I'm trying to implement a soft-delete model in my project. To that end, I want to be able to filter out deleted objects by default. At the same time, I want to keep all my QuerySet filters in one place and accessible as MyModel.objects. I also want to be able to chain my filtering methods, so I'm looking towards using MyQuerySet.as_manager() as the manager for such models. Thus it looks like I need to extend Django's QuerySet, but add a custom default filter. However, I can't figure out how to do that. The following code does not look like a great idea. class MyQuerySet(models.QuerySet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self = self.filter(deleted=False) I also tried to figure out how to use Manager.from_queryset() for that purpose, but I still don't see how to make a manager that would be reusable, that is one that I could inherit from and be able to add my own QuerySet methods and still have the default filtering. -
Why we use serializers instead of full clean to validate models or should we use them interchangeably?
I am working on a API server which uses Django Rest Framework. I have been using model's clean method to validate my models and calling full clean in views. It does not work properly for every situation. I sense there are some mistakes in my logic. I have never used any serializer and don't know should i use it or not while using full clean. So my question is how can I validate my models in a proper way. -
Foreign keys in django
Ok so I have a table named Courses where CourseCode and Pattern act as composite primary key. Now in another table called delivery_methods same CourseCode and pattern should act as foreign key for their respective attributes in table Courses. So how can I do that in django model -
Can't login Django admin with valid user and password on development environment (runserver)
I can't log into Django with my valid username and password. Its giving me the standard error: "Please enter a correct username and password. Note that both fields may be case-sensitive." I have even tried to create a new admin with python manage.py createsuperuser but even then I can't log into the new staff account. I checked and made sure that I have a django_session table in my database, but the expire_date and before today. I am using Django 2.2 I haven't logged into this project in a few months so I am not sure if that has anything to do with it? Thanks so much in advance! -
Not able to import module from another packages in python 3.6
I want to import models.py file from gameplay package in player.views.py file but getting error: No module named game.gameplay I've already tried: from game.gameplay.models import Game from ..gameplay.models import Game The structure of my project is: project | | |--game(package) | | | |--gameplay(package) | | | | | |--__init__.py | | |--models.py | | | |--player(package) | | | | | |--__init__.py | | |--views.py | | | |--manage.py | |--venv -
Django CMS - cookie cutter : The form could not be loaded. Please check that the server is running correctly
I started learning web development at a company, and was tasked with making a simple app in cookiecutter django, and then integrating django-cms into it. I used django cookie-cutter to start a project, and then integrated django-cms into the project following this guide : https://github.com/pydanny/cookiecutter-django http://docs.django-cms.org/en/latest/how_to/install.html After some initial trouble, I managed to get it going. After that, the next step was to add my "polls" app to the project and integrate Django CMS in it aswell. For that I followed this tutorial : http://docs.django-cms.org/en/latest/introduction/03-integrating_applications.html#incorporate-the-polls-application I managed to get all the way to the end of the last link, and then on step 6, this happens. Every time I try to delete a plugin from my site, or when I click create on the CMS toolbar i get this error (note: if I log in to /admin, I can create the page, but not via the cms menu bar on the actual website) : The form could not be loaded. Please check that the server is running correctly. And in the console : Refused to display 'http://127.0.0.1:8000/cms_wizard/create/?page=5&language=en&edit&cms_path=/home/?edit&language=en&structure' in a frame because it set 'X-Frame-Options' to 'deny'. bundle.toolbar.min.js:1 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental … -
Why Union of two Django querysets not working
I have tried to get union of some queryset but got unexpected result. Can you please help me I have also check with How can I find the union of two Django querysets? but its not working as well. Here i have attached image to show my tries. in the above image i get four queryset( qs, qs1 , qs2, my_qs ) after filter BetDetails objects here i want to get result in my_qs And when i tried to merge/Union of the queryset got on blank queryset in my_qs While i have data in qs1 . expected result should be <QuerySet [<BetDeetails: BetDetails object (29)>]> But i got : <QuerySet []> I don't know why its showing this type of result. Can anyone please explain and guide me to get desired result. -
How to pass credentials with redux to django API
My Django API is protected as follows: class cars(ListAPIView): permission_classes = [ permissions.IsAuthenticated, ] I would like to get the data using redux, but I am not sure how to pass my credentials along with my redux call ? Here is my redux call export const Search_Results = (name, getState) => { return dispatch => { axios.get(`http://127.0.0.1:8000/api/?name=${name}`, tokenConfig(getState)) .then(res => { dispatch(presentResult(res.data)) }); } }; It returns an error, as it does not like how tokenConfig(getState)) is passed. When I am in that page I can clearly see there is a token using the dev_tools. When I remove the tokenConfig part from the call I get xhr.js:166 GET http://127.0.0.1:8000/api/auth/user 401 (Unauthorized) And when I remove permission class from the API, then I can get all the data using the same redux call. Here is the action for tokenConfig for the curious // Setup config with token - helper function export const tokenConfig = getState => { // Get token from state const token = getState().auth.token; // Headers const config = { headers: { "Content-Type": "application/json" } }; // If token, add to headers config if (token) { config.headers["Authorization"] = `Token ${token}`; } return config; }; -
How to paginate on distinct times value shows up in query set?
I have a model of songs, this table contains single tracks and album tracks. These are separated using a column which is true or false based on type of track. I am retrieving back the results of albums, however I need pagination so I am not getting back all results and slowing down query. But with albums and pagination I have some tracks from the last album get cut off and end up on page 2. How can I do pagination by the distinct amount of times an album shows up. Let's say I want to paginate 50 albums regardless of how many tracks they have. Each album track entry has a specific column which has the same exact value to connect them as an album. -
How to delete row with the least id using Django ORM?
I'm wondering what is the idomatic Django equivalent of: DELETE FROM article WHERE ID = ( SELECT Min( ID ) FROM article ) What I have tried is to retrieve the article with the lowest id article = Article.objects.all().order_by("-id")[:1] And then: Article.objects.filter(id=article.id).delete() But I'm wondering if there is more efficient/elegant way to do so? -
TemplateDoesNotExist at / for a Django compiled project using PyInstaller
I am trying to run a Django project using an EXE file compiled using Pyinstaller. But when I run the compiled .EXE file using this command I get TemplateDoesNotExist at /. dj.exe runserver localhost:8000 First I installed Pyinstaller using the command: pip install pyinstaller Then I installed OSGeo4W64 on my Windows 10 machine for GDAL. I added this in settings.py: import os if os.name == 'nt': import platform OSGEO4W = r"C:\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] os.environ['DJANGO_SETTINGS_MODULE'] = 'dj.settings' SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) TEMPLATE_DIRS = ( os.path.join(SETTINGS_PATH, 'templates'), ) GEOS_LIBRARY_PATH = r'C:\OSGeo4W64\bin\geos_c.dll' GDAL_LIBRARY_PATH = r'C:\OSGeo4W64\bin\gdal204.dll' I also generated a spec file using this command: pyi-makespec dj/manage.py And this is the generated manage.spec: # -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis(['dj\\manage.py'], pathex=['C:\\Users\\omen\\Desktop'], binaries=[], datas=[('app/templates','app/templates')], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name='manage', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, console=True ) coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, upx_exclude=[], name='manage') I added in datas the … -
how to fix this error in opencv django error:(-215:assertion failed) !_src.empty() in function 'cv::cvtcolor' in djang
im woking with my capstone project and im using django as the backend framework for face recognition attendance system using OPENCV, getting image and training the image are working perfectly, but when I start the system to detect faces in the camera it trows error. OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor' i need help please T_T im using python 3.6, django 2.2, opencv 4.1 def getattendance(request): if not os.path.exists('./ImagesUnknown'): os.makedirs('./ImagesUnknown') fname = "recognizer/trainingData.yml" if not os.path.isfile(fname): print("Please train the data first") exit(0) face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') cap = cv2.VideoCapture(0) print(cap.isOpened()) recognizer = cv2.face.LBPHFaceRecognizer_create() recognizer.read(fname) while True: ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3) ids,conf = recognizer.predict(gray[y:y+h,x:x+w]) profile = Profile.objects.get(id=ids) name = profile.first_name cid = str(profile.church_id) if conf < 50: cv2.putText(img, 'Name: '+name, (x+2,y+h+35), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255),2) cv2.putText(img, 'ID no.: '+cid, (x+2,y+h+65), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255),2) # Hour,Minute,Second=timeIn.split(":") # c.execute('INSERT OR IGNORE INTO attendance (name,cid,timeIn,date) VALUES (?,?,?,?)', (name,cid,str(timeIn),str(date))) # conn.commit() else: cv2.putText(img, 'Unkown', (x+2,y+h-5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255),2) noOfFile=len(os.listdir("ImagesUnknown"))+1 cv2.imwrite("ImagesUnknown/Image"+str(noOfFile) + ".jpg", img[y:y+h,x:x+w]) cv2.imshow('Face Recognizer',img) if cv2.waitKey(20) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()