Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Socket io + django rest framework + Vue
I am developing a web application with drf in backend and vue in frontend. I need to add Chat functionality. For that socket io is great solution. But i can not find any tutorials or documentation to do that. Please help me. -
How to fetch data from api and display all fields data in your Django projects
i have some problam in the url_field. how to fetch url data and display the full content of the urlenter image description here -
Django how to implement auto logout and auto login together?
I am working on a project in Django. Everything works well. But I am having some clash in the implementation of Automatic logout after a certain duration of inactivity and Automatic login functionality if a user closes tab without logging out and reopens tab. Problem 1- Need Automatic Logout functionality after 1 hour of inactivity. Implemented and works. 2- Need Automatic Login Functionality. Meaning if a user hasn't logged out and closes tab, and tries to reach the /login url, he must be taken to dashboard as he never logged out. Implemented and works. Both these functionalities work but not when they are implemented together. What has been implemented? 1- For Logout: SESSION_COOKIE_AGE = 60*60 SESSION_SAVE_EVERY_REQUEST = True Implemented in settings.py. 2- For Login: In my login view function in POST case I have implemented cookies. I am setting cookies for username using response.set_cookie('username', username) Then in GET I am checking if the cookie of 'username' is set or not. If it is set I take user to dashboard. Else I take him to login page. 3- In /logout view I am deleting cookie of 'username' as: response.delete_cookie('username') The Problem arising is that if the time of 1 hour is … -
How to pass data from html template (using html form) to views.py python in django?
I am trying to get input from a html form to python views.py file in django. Below is my html and python code: <form action="getsummary" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="exampleFormControlTextarea1">Paste your text here</label> <textarea class="form-control" name="inputText" id="exampleFormControlTextarea1" rows="10" style="width:1000px; "></textarea> </div> </form> <div class="d-flex justify-content-center"> <div class="border d-flex justify-content-center" style="width:160px"> <a href="getsummary"> <button type="submit" class="btn btn-primary">Summarize Now</button> </a> </div> </div> def getsummary(request): if request.method == "POST": title = request.POST.get('inputText') print(title) return render(request, 'get-summary.html' ) I gave input text in my html form. My terminal was supposed to print that text but instead its printing Nothing. [15/Feb/2022 12:20:33] "GET /summary HTTP/1.1" 200 2514 [15/Feb/2022 12:20:36] "GET /getsummary HTTP/1.1" 200 1961 I also tried doing it with GET method. In that case, it is printing None. Kindly help me with this. Same issue I am facing when I am using ajax to pass javascript variable to views.py python file. Thank you. -
Adding a Spreadsheet Attachment in Django and Generating Monthly reports
I am trying a timesheet project. I am using Django rest-framework and using Postgres as my database. My client requested me that he need a spreadsheet functionality like a particular admin must have monthly spreadsheet reports of his employees every month and that process should be automated. As I am new to Django, Kindly guide me through this process **utitles.py** import threading from django.core import mail class EmailThread(threading.Thread): def __init__(self, subject, plain_message, from_email, to_email): self.subject = subject self.plain_message = plain_message self.from_email = from_email self.to_email = to_email super(EmailThread, self).__init__() def run(self): mail_send = mail.send_mail(self.subject, self.plain_message, self.from_email [self.to_email]) print('mail send successfully ', mail_send) **serializers.py** class UserSerializers(serializers.ModelSerializer): def create(self, validate_data): subject = 'Your account was activated' plain_message = 'SAMPLE TEXT' from_email = 'demomaster147@gmail.com' to_email = validate_data['email'] attach_files = ['Client-2022-02-04.xls'] EmailThread(subject, plain_message, from_email, to_email,attach_files).start() return Users.objects.create(**validate_data) **settings.py** EMAIL_HOST = 'smtp.gmail.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_PORT = 587 EMAIL_HOST_USER = 'demoma@gmail.com' EMAIL_HOST_PASSWORD = '**********' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER -
Automatically calculating a ModelForm field on users click
I currently have a section in my form that looks like this: With this form , I need to calculate Provisional Tax Date 1 and Provisional Tax Date 2 based on the Financial Year End Field ( Provisional Tax Date 1 must be 6 months after Financial Year End & Provisional Tax date 2 needs to be on the 31st of December on the year of the Financial Year End) I would also need this to happen live, so as soon as the user changes the Financial Year End field it will update the other 2 If anyone has some sample code to assist with this, it would be highly appreciated. Please see the below code from my project: Views.py: def newCompany(request): form = CompanyForm() if request.method == 'POST': form = CompanyForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: print(form.errors) content = {'form':form} return render(request, 'main/newCompany.html', content) Models.py class CompanyClass(models.Model): CompanyName = models.CharField(max_length=50 , blank=False) RefNo = models.CharField(max_length=50 , blank=False ) FinancialYearEnd = models.DateField(auto_now=False, auto_now_add=False, null=False) ProvisionalTaxDate1 = models.DateField(auto_now=False, auto_now_add=False) ProvisionalTaxDate2 = models.DateField(auto_now=False, auto_now_add=False) ARMonth = models.DateField(auto_now=False, auto_now_add=False) checklist=models.ManyToManyField(Task) def __str__(self): return ( self.CompanyName) Forms.py class CompanyForm(ModelForm): class Meta: model = CompanyClass fields = '__all__' widgets = { 'FinancialYearEnd' : forms.SelectDateWidget, … -
Django receives multiple posts from the browser, Does the browser cache POSTs?
During developement it happens like this: if I am working on a piece of code to receive a POST request; Django will serve up an error page because the code is buggy. Then I fix a syntax error, refresh, a different error, fix that, repeat the process say 8 times. But on the 8th time the code works, and then Django receives and stores 8 Post entries, not just the last one! A similar behavior happens in production very occasionally. I am not sure if it is the browser caching the POSTs, then sending them all through at the same time or Django? I wrote javascript code to disable the submit button once clicked. I also check for duplicate entries (within a 5 seconds window) before saving, but it only works if one manually submits twice in quick succession, not if it auto sends a bunch of POSTs at the same time. These both are "hacks" that don't address the root cause. Any clue on how to debug or ways to attempt to solve/debug the issue? -
NameError at/ name 'Product' is not defined
I've been working on this ecommerce website and its been working perfectly but today when I ran the server it's showed me " NameError at/ name 'Product' is not defined" I've looked Into the code several times and didn't spot any error Models.py Class Product(models.Model): "" "" def __str__(self) self.name Views.py From .models import * def ShowProducts(request): items= Product.objects.all() context = {'items':items} return render(request, 'home.html', context=context) urls.py from . import views urlspatterns=[ Path ('', views.ShowProducts, name ='showproducts') ] My greatest surprise is , when I change the line, 'item= Product.objects.all()' to 'items= ()' in views.py,. It deplays the website correctly although without any product in it, please what should I do -
Joinging Query Django
class PopSummary(models.Model): available_pop = models.PositiveIntegerField(default=0) email = models.EmailField( verbose_name="email address", max_length=255, unique=True, default='' ) requested_pop = models.PositiveIntegerField(default=0) approved_pop = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) approve = models.BooleanField(default=False) popuser = models.ForeignKey(RequestPop, on_delete=models.CASCADE,related_name='popuser',null=True) def __str__(self): return "{}-{}".format(self.email,self.available_pop) Another Table: class RequestPop(models.Model): request_pop = models.PositiveIntegerField(default=0) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE,unique=False,null=True) created_at = models.DateTimeField(auto_now_add=True) available_pop = models.PositiveIntegerField(default=0) def __str__(self): return "{}-{}".format(self.user,self.request_pop) I want to make the query in inner join or other way so that: select all from RequestPop where PopSummary.approve=True I run the follwing query. queryset = RequestPop.objects.filter(popuser__approve=True).all() but it seems to be incorrect. So what should be the solution for it please. -
How to undo a path command in cmd
I am learning django and was trying to run a webapp but I mistakenly pasted "path('admin/', admin.sites.urls)" (without double quotes) and it ran automatically. Now none of the python commands are working, and I can't come out of my virtual environment. How can I revert this? Here is the command -
Django view exception logs with INFO level, not ERROR
views.py def error(request): logger.error('logger.error - test error') raise Exception('raise Exception - test error') 1st logging settings: # 1 LOGGING = { 'version': 1, 'disable_existing_loggers': False, # True in dictConfig default 'formatters': { 'syslog': { 'format': 'django %(levelname)s %(name)s %(process)d %(thread)d %(message)s' }, }, 'handlers': { 'syslog': { 'class': 'logging.handlers.SysLogHandler', 'formatter': 'syslog', 'facility': 'local1', 'address': '/dev/log' }, }, 'loggers': { 'django': { 'handlers': ['syslog'], 'level': 'ERROR', 'propagate': True, }, '': { 'handlers': ['syslog'], 'level': 'ERROR' }, }, 'root': { 'handlers': ['syslog'], 'level': 'ERROR' } } 1st logs (2 files in django dir) sudo tail /var/log/my_proj/django/syslog.info <*NO log!> sudo tail /var/log/my_proj/django/syslog.error 2022-02-15T09:49:43.019832+05:00 my_proj-stage-main1 django ERROR apps.demo.views 180029 140050762920576 logger.error - test error 2nd logging settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, # True in dictConfig default 'formatters': { 'syslog': { 'format': 'django %(levelname)s %(name)s %(process)d %(thread)d %(message)s' }, }, 'handlers': { 'syslog': { 'level': 'INFO', 'class': 'logging.handlers.SysLogHandler', 'formatter': 'syslog', 'facility': 'local1', 'address': '/dev/log' }, }, 'loggers': { 'django': { 'handlers': ['syslog'], 'level': 'INFO', 'propagate': True, }, '': { 'handlers': ['syslog'], 'level': 'INFO' }, }, 'root': { 'handlers': ['syslog'], 'level': 'INFO' } } 2nd log (2 files in django dir) sudo tail /var/log/my_proj/django/syslog.info 2022-02-15T10:00:37.377018+05:00 my_proj-stage-main1 django INFO django.request 185769 140536088752768 OK: /ru/demo/error#012Traceback … -
list indices must be integers or slices, not dict in django
I just want to iterate through the list of JSON data which I get in the payload but getting an error as list indices must be integers or slices, not dict payload: [{"AuditorId":10,"Agents":"sa","Supervisor":"sa","TicketId":"58742","QId":150,"Answer":"Yes","TypeSelected":"CMT Mails","Comments":"na","TicketType":"Regularticket","Action":"na","AuditSubFunction":"na","AuditRegion":"na"},{"AuditorId":10,"Agents":"sa","Supervisor":"sa","TicketId":"58742","QId":151,"Answer":"Yes","TypeSelected":"CMT Mails","Comments":"na","TicketType":"Regularticket","Action":"na","AuditSubFunction":"na","AuditRegion":"na"}] views.py: @api_view(['POST']) def SaveUserResponse(request): for ran in request.data: auditorid = request.data[ran].get('AuditorId') ticketid = request.data[ran].get('TicketId') qid = request.data[ran].get('QId') answer = request.data[ran].get('Answer') sid = '0' TicketType = request.data[ran].get('TicketType') TypeSelected = request.data[ran].get('TypeSelected') agents = request.data[ran].get('Agents') supervisor = request.data[ran].get('Supervisor') Comments = request.data[ran].get('Comments') action = request.data[ran].get('Action') subfunction = request.data[ran].get('AuditSubFunction') region = request.data[ran].get('AuditRegion') cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] @auditorid=%s,@ticketid=%s,@qid=%s,@answer=%s,@sid=%s,@TicketType=%s,@TypeSelected=%s,@agents=%s, @supervisor =%s, @Comments=%s, @action=%s, @subfunction=%s, @region=%s', (auditorid,ticketid,qid,answer, sid,TicketType, TypeSelected, agents, supervisor, Comments, action, subfunction,region)) return Response(True) -
Is it possible to use complex logic in DRF ViewSet Permission Classes?
In the app I'm working on, I'd like it so that to create a task for a committee, you must be a member of the committee, the head of the committee, or an admin user, but you must also be authenticated. I understand this can be done with a few OR operators, but in the case that I need something more complex, I was hoping I could use nested lists of permission classes as such: permission_classes = [ IsAuthenticated & [ IsCommitteeHead | IsCommitteeMember | IsAdminUser ] ] Will this syntax work properly, or does rest_framework not understand this? -
Ubuntu Apache taking long time to respond and getting This site can’t be reached
Hi Guys I am trying to route my domain to server 139.5X.X.XXX Following is My DNS record Details in Hostinger :- Type Name Priority Content IP-V4 TTL A www 0 139.5X.X.XXX 600 A @ 0 139.5X.X.XXX 14400 Now I am seeing default apache page while browsing the domain (Server serving default apache page (Digital Ocean Ubuntu Droplet)) . But after configuring a Django service to domain it taking too long to respond and ending up with "This Site can't be Reached" following is the conf file which I am using <VirtualHost *:80> ServerName tellie.in ServerAlias www.tellie.in Redirect permanent / https://tellie.in/ RewriteEngine on RewriteCond %{SERVER_NAME} =tellie.in [OR] RewriteCond %{SERVER_NAME} =www.tellie.in RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> <VirtualHost *:443> ServerAdmin admin@tellie.in ServerName tellie.in ServerAlias www.tellie.in DocumentRoot /home/srv/telli ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/srv/telli/telli/static <Directory /home/srv/telli/telli/static> Options FollowSymLinks AllowOverride None Require all granted </Directory> Alias /media /home/srv/telli/telli/media <Directory /home/srv/telli/telli/media> Options FollowSymLinks AllowOverride None Require all granted </Directory> <Directory /home/srv/telli/telli/telli> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess telli python-path=/home/srv/telli/telli python-home=/home/srv/telli/venv WSGIProcessGroup telli WSGIScriptAlias / /home/srv/telli/telli/telli/wsgi.py Include /etc/letsencrypt/options-ssl-apache.conf SSLCertificateFile /etc/letsencrypt/live/tellie.in/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/tellie.in/privkey.pem </VirtualHost> Is there anything wrong that could cause the problem I am facing -
Django Subquery many values
class Category(models.Model): name = models.CharField(max_length=100) date = models.DateTimeField(auto_now=True) class Hero(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) I want Categoty model name, data, id In cookbook , I wrote the code as above. hero_qs = Hero.objects.filter( category=OuterRef("pk") ).order_by("-benevolence_factor") Category.objects.all().annotate( most_benevolent_hero=Subquery( hero_qs.values('name')[:1] ) ) It seems that only one value can be entered in hero_qs.values('name') Is it possible to get name, data, id with one annotate? -
Using ffmpeg to edit images in python
I have to use ffmpeg library in django. I have already installed ffmpeg using : pip install ffmpeg-python The following tasks are to be performed : Take an image as input which in the form of a url (eg : https://imgd.aeplcdn.com/0x0/cw/ec/30146/MercedesBenz-CClass-Right-Rear-Three-Quarter-136699.jpg?wm=0) this is an input image for me Process the image using ffmpeg to : a. remove its background b. crop 30px from bottom c. resize image size to 550 by 300 Return the processed image in form of a url. And the entire code is to be incorporated in working python(django) code. How to write this piece of code so that the above mentioned functions are performed? -
Is it possible to use Form Mixin with ListView and submit multiple values with one button?
Is it possible to use a list view in order to implement a quiz style layout? I am attempting to build a quiz app that takes a list view and ask a question after each instance of a class. The problem I am having is I cant figure out how to have my form submit and send all of my values at once in a post method. class GameListView(FormMixin,ListView): form_class = AnswerForm model = Game def get_success_url(self): return reverse('gameAPP:gameList') def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): answer = form.cleaned_data['answer'] return super().form_valid(form) #Models class Game(models.Model): player = models.ForeignKey('auth.User', on_delete=models.CASCADE) question = models.CharField(max_length=1000) correctAnswer = models.CharField(max_length=1000) def answer_onion(self): print(True) Answer.answer = True #Answer.answer.save() def answer_other(self): print(False) Answer.answer = False #Answer.answer.save() class Answer(models.Model): question = models.ForeignKey('gameAPP.Game', on_delete=models.CASCADE, related_name="games") answer = models.BooleanField(null=True) #form class AnswerForm(forms.ModelForm): class Meta: model = Answer fields = ('answer', ) #my view: {% for g in game_list %} <h1>question: {{ g.question }}</h1> <h3>correct answer: {{g.correctAnswer }} </h3> {{form}} {% endfor %} <button type="submit">Submit</button> -
How can I customize filtering in DJango Admin?
admin.py class authUserMenu(admin.ModelAdmin): list_display = ["__str__", "user_id", "menu_id","is_active"] class Meta: Model = AuthUserMenu admin.site.register(AuthUserMenu, authUserMenu) models.py class AuthUserMenu(models.Model): # USER VS MENU relation user = models.ForeignKey(AuthUser,on_delete=models.DO_NOTHING,blank=True, null=True) menu = models.ForeignKey(Menu,on_delete=models.DO_NOTHING,blank=True, null=True) is_active = models.BooleanField(default=False) class Meta: db_table = 'auth_user_menu' ordering = ['user','menu','is_active'] def __str__(self): # return self.id return str([self.user.username,'>>>>>>', self.menu.menu_name]) In my Django admin panel When filtering with username should only show some menus under some condition... How can I achieve this? Suppose here for the username 4 menu is showing. But it should show 2 menu. This may obtain by db querying. -
What is the efficient way: run the same function on Server-Side or on Client-Side
I am currently coding a web application using Django (4.0) with Django REST Framework for Server-Side Python scripts and NextJS for Client-Side Javascript. I have a function implemented in Python that helps to upload an image to IPFS and returns an image URI in order to display the image on the web page. Besides that, I have also a Javascript code that does exactly the same but on the Client-Side. What's the efficient way as for the speed and energy consumption to run that function: whether on Client-Side in the browser with JS or better to do this on the Server-Side and return the value through HTTP with DRF? Note: Client and server are on the same network. -
Is possible paginate multiple arrays with templateView in different contexts?
I am working on a view with 2 tabs, in each tab a different list should be displayed. Here's an example of views.py file. '''python3 class IndexView(LoginRequiredMixin, TemplateView): template_name = 'index.html' login_url = reverse_lazy('login') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) today = datetime.today() start_week = today - timedelta(today.weekday()) end_week = start_week + timedelta(7) context['dayli_expirations'] = Member.objects.filter( expiration_date__day=today.day, expiration_date__month=today.month, expiration_date__year=today.year ) context['weekly_expirations'] = Member.objects.filter(expiration_date__range=[start_week, end_week]) return context ''' -
Django orm Subquery model object
Cookbook link Cookbook said that if you do the above, you can bring the value. hero_qs = Hero.objects.filter( category=OuterRef("pk") ).order_by("-benevolence_factor") Category.objects.all().annotate( most_benevolent_hero=Subquery( hero_qs.values('name')[:1] ) ) I want the object of the Hero model. -
SQL cleaning function in python
So I have a message field on a form and I want to save the message into a database column named help_desk_message. I know that Django already tries to handle sql injection for you but I want to do a bit more. I want to clean my help_desk_message in my Views.py before saving it to the database by sending it to a function. so I would pass my message into a function sql_message_cleaner(help_desk_message). I need help with the function that cleans out the sql injection. I tried writing it but it failed. I need the function in Python -
Django explanation of HyperLinkedSerializer URL Lookups
I am relatively new to Django Rest Framework and have just spent an hour figuring out how HyperlinkedSerializer class matches URLs. This unfortunately left me more confused than anything. I am using DRF nested routers and the definition for both serializers and routers is below # serializers.py class RecordingFolderSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = RecordingFolder fields = [...] # urls.py from rest_framework_nested import routers from my_app import views # ... router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) # Somehow fixes the error shown below: router.register('folders', views.RecordingFolderViewSet) # WHY DOES THIS FIX MY ISSUE! recording_router = routers.NestedSimpleRouter(router, r'users', lookup='user') # Original version which caused the error before I added the folder view to the base router recording_router.register('folders', views.RecordingFolderViewSet, basename='user-folders') urlpatterns = [ path('admin/', admin.site.urls), path(r'', include(router.urls)), path(r'', include(recording_router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] Not having the line that attaches the folder to the base router produces this error when I try and go to users/id/folders/folder_id: Could not resolve URL for hyperlinked relationship using view name "recordingfolder-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. My questions are twofold: First, if I have one specific view on users, such as users/id/profile … -
no such file libmariadb.3.dylib error when importing MySQLdb on mac M1
I migrated my data to M1 Monterey MacOS from intel macmini. I was happy to use django and mariadb until I installed a package using homebrew. I installed homebrew and installed vim with it, and then my django-mariadb connection suddenly stopped working. I found out that the error was caused in python3.7/site-packages/MySQLdb/init.py in 18th line in my venv. try: from MySQLdb.release import version_info from . import _mysql # this line causes the problem assert version_info == _mysql.version_info except Exception: raise ImportError( "this is MySQLdb version {}, but _mysql is version {!r}\n_mysql: {!r}".format( version_info, _mysql.version_info, _mysql.__file__ ) ) And the stacktrace goes Traceback (most recent call last): File "/Users/gwanghyeongim/Documents/revhat/basecamp/.venv/basecamp/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/gwanghyeongim/Documents/revhat/basecamp/.venv/basecamp/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 0x0002): Library not loaded: /usr/local/opt/mariadb/lib/libmariadb.3.dylib Referenced from: /Users/gwanghyeongim/Documents/revhat/basecamp/.venv/basecamp/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so Reason: tried: '/usr/local/opt/mariadb/lib/libmariadb.3.dylib' (no such file), '/usr/lib/libmariadb.3.dylib' (no such file) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/gwanghyeongim/Documents/revhat/basecamp/.venv/basecamp/lib/python3.7/site-packages/MySQLdb/__init__.py", line 24, in <module> version_info, _mysql.version_info, _mysql.__file__ NameError: name '_mysql' is not defined I had written a post about _mysql not defined some time ago, and I fixed the problem by exporting a path in my ~/.zshrc. But this time I googled … -
How to apply for loop in Django's views.py
[research/models.py] RECRUITING_CHOICES = [ ('Recruiting', 'Recruiting'), ('Not yet recruiting', 'Not yet recruiting'), ('Completed', 'Completed'), ('Holding', 'Holding'), ] RECRUITING_CHOICES_INV = {val: val for val, _ in RECRUITING_CHOICES} class Research(models.Model): is_deleted = models.BooleanField(default=False) is_recruiting = models.CharField(choices=RECRUITING_CHOICES, null=True, max_length=50) research_name = models.CharField(max_length=2000, null=True) teacher= models.CharField(max_length=2000, null=True) I'm using Django, and I'm trying to create a list for generating apexchart (graph) in views.py using a class model 'Research'. I am trying to add each of the 4 values of the is_recruiting field to filtering , but adding Recruiting and Not yet Recruiting just takes multiple lines and makes the code look inefficient. Is there a workaround using the for statement? [research/views.py] counts = Research.objects.values('teacher') \ .annotate(A=Count('id', filter=Q(type='A')), B=Count('id', filter=Q(type='B')), C=Count('id', filter=Q(type='C')), D=Count('id', filter=Q(type='D')), E=Count('id', filter=Q(type='E')), F=Count('id', filter=Q(type='F')), r_A=Count('id', filter=Q(type='A', **is_recruiting='Recruiting'**)), r_B=Count('id', filter=Q(type='B', **is_recruiting='Recruiting'**)), r_C=Count('id', filter=Q(type='C', **is_recruiting='Recruiting'**)), r_D=Count('id', filter=Q(type='D', **is_recruiting='Recruiting'**)), r_E=Count('id', filter=Q(type='E', **is_recruiting='Recruiting'**)), r_F=Count('id', filter=Q(type='F', **is_recruiting='Recruiting'**)), N_A=Count('id', filter=Q(type='A', **is_recruiting='Not yet recruiting'**)), N_B=Count('id', filter=Q(type='B', **is_recruiting='Not yet recruiting'**)), N_C=Count('id', filter=Q(type='C', **is_recruiting='Not yet recruiting'**)), N_D=Count('id', filter=Q(type='D', **is_recruiting='Not yet recruiting'**)), N_E=Count('id', filter=Q(type='E', **is_recruiting='Not yet recruiting'**)), N_F=Count('id', filter=Q(type='F', **is_recruiting='Not yet recruiting'**))) \ .values('teacher', 'A', 'B', 'C', 'D', 'E', 'F', 'r_A', 'r_B', 'r_C', 'r_D', 'r_E', 'r_F', 'N_A', 'N_B', 'N_C', 'N_D', 'N_E', 'N_F')