Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
return qs._result_cache[0] IndexError: list index out of range [12/Jul/2022 14:43:28] "GET /shop/products/15 HTTP/1.1" 500 68001
return qs._result_cache[0] IndexError: list index out of range [12/Jul/2022 14:43:28] "GET /shop/products/15 HTTP/1.1" 500 68001 -
Why two ViewSets have identical url in DRF?
Why two different viewsets have identical url? How can I change it? router = routers.DefaultRouter() router.register(r'general-worker', GeneralWorkerViewSet) router.register(r'full-info-worker', FullInfoWorkerViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include(router.urls)), path('api/v1/drf-auth/', include('rest_framework.urls')), ] json from http://127.0.0.1:8000/api/v1/ { "general-worker": "http://127.0.0.1:8000/api/v1/full-info-worker/", "full-info-worker": "http://127.0.0.1:8000/api/v1/full-info-worker/" } -
Update Database Column and Tables with Django
I've encounter into a situation where i try to update mysql database using django. here is the schema of it: the original schema class Departments(models.Model): DepartmentId = models.AutoField(primary_key=True) DepartmentName = models.CharField(max_length=100) class Groups(models.Model): GroupId = models.AutoField(primary_key=True) GroupName = models.CharField(max_length=100) class Employees(models.Model): EmployeeID = models.AutoField(primary_key=True) EmployeeName = models.CharField(max_length=100) Departments = models.CharField(max_length=100) Groups = models.CharField(max_length=100) DateOfRecruitment = models.DateField() Position = models.CharField(max_length=100) PhotoFileName = models.CharField(max_length=100) the new schema class Departments(models.Model): DepartmentId = models.AutoField(primary_key=True) DepartmentName = models.CharField(max_length=100) class Groups(models.Model): GroupId = models.AutoField(primary_key=True) GroupName = models.CharField(max_length=100) class Positions(models.Model): PositionId = models.AutoField(primary_key=True) PositionName = models.CharField(max_length=100) class Employees(models.Model): EmployeeID = models.AutoField(primary_key=True) EmployeeName = models.CharField(max_length=100) Departments = models.CharField(max_length=100) Groups = models.CharField(max_length=100) DateOfRecruitment = models.DateField() DateOfResignation = models.DateField() Position = models.CharField(max_length=100) Blacklist = models.BooleanField() BlacklistDate = models.DateField() PhotoFileName = models.CharField(max_length=100) I've tried to use the following command python manage.py makemigrations someapp python manage.py migrate However it doesn't update within the mysql system itself. The only solution that i came out of is dropping the entire database and make the migration again. I hope that there is a better solution than my method as i couldn't just use the same method for data migration or another table update. Thank you. -
How to get difference between two dates as a integer inside Django templates
I have list of two dates: ['2022-07-11', '2022-07-19'] and have to calculate difference between them as a int value: 8 inside Django templates. I tried with: {% with value1=date.value.1 value0=date.value.0 %} <h3>{{ value1-value0 }}</h3> {% endwith %} Error: Could not parse the remainder: '-value0' from 'value1-value0' I also tried with timesince and timeuntilstill no result Any way to get just get difference between as a int -
Every log file capturing all the apps logs, irrespective of which app is running
I was trying to create a separate log file for every app . But my every log file is capturing all the log data irrespective of which app is running. I tried like below, In my setting.py file i have the below code INSTALLED_APPS = [ 'src.admin_management', 'src.change_management', ] LOG_DIR = BASE_DIR + '/application_logs/' LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'null': { 'level':'DEBUG' if DEBUG else 'WARNING', 'class':'logging.NullHandler', }, 'src.admin_management': { 'level':'DEBUG' if DEBUG else 'WARNING', 'class':'logging.handlers.RotatingFileHandler', 'filename': LOG_DIR + "/admin_management.log", 'maxBytes': 1024 * 1024 * 10, #Max 10MB 'backupCount': 3, 'formatter': 'standard', }, 'src.change_management': { 'level':'DEBUG' if DEBUG else 'WARNING', 'class':'logging.handlers.RotatingFileHandler', 'filename': LOG_DIR + "/change_management.log", 'maxBytes': 1024 * 1024 * 10, #Max 10MB 'backupCount': 3, 'formatter': 'standard', }, # 'console':{ # 'level':'INFO', # 'class':'logging.StreamHandler', # 'formatter': 'standard' # }, }, 'loggers': { 'django': { # 'handlers':['console'], 'propagate': True, 'level':'WARN', }, 'django.db.backends': { # 'handlers': ['console'], 'level': 'DEBUG' if DEBUG else 'WARNING', 'propagate': False, }, '': { 'handlers': [ 'src.admin_management', 'src.change_management', ], 'level': 'DEBUG', }, } } I have the below code in my views.py file in the admin_management app import … -
Setting django to server media files from google cloud
I'm trying to deploy my project in Heroku but the media files (images) are deleted , so someone told me that i need to use a service called "Google cloud", my question is, how to configure my prject to use that service. Can somebody help me? -
"(1452, Cannot add a foreign key constraint fails( CONSTRAINT `FK_STG_TRN_DATA_LOCATION` FOREIGN KEY (`LOCATION`) REFERENCES `location` (`LOCATION`))
@csrf_exempt def stg_trn(request): if request.method == 'POST': try: json_object = json.loads(request.body) current_user = request.user D_keys=[] data_list=[] l_counter=0 for row in json_object: for key in row: if row[key]=="" or row[key]=="NULL": D_keys.append(key) for key in D_keys: row.pop(key) D_keys.clear() l_counter=l_counter+1 d= str(datetime.now()).replace('-',"").replace(':',"").replace(' ',"").replace('.',"") unique_id=d+str(l_counter)+'STG' row["TRAN_SEQ_NO"]=unique_id row["PROCESS_IND"]='N' row["CREATE_DATETIME"]=str(datetime.now()) row["CREATE_ID"]=str(current_user) row["REV_NO"]=1 json_object=json_object[0] mycursor = connection.cursor() #Comparing and assign values to the Foreign key values based on input parameters. res1=mycursor.execute("SELECT LOCATION FROM LOCATION WHERE LOCATION="+'"'+(str(json_object["LOCATION"]))+'"') res1=mycursor.fetchall()[0][0] row["LOCATION"]=res1 print(res1) res2=mycursor.execute("SELECT ITEM FROM ITEM_DTL WHERE ITEM="+'"'+(str(json_object["ITEM"]))+'"') res2=mycursor.fetchall()[0][0] row["ITEM"]=res2 res3=mycursor.execute("SELECT CURRENCY FROM CURRENCY WHERE CURRENCY="+'"'+(str(json_object["CURRENCY"]))+'"') res3=mycursor.fetchall()[0][0] row["CURRENCY"]=res3 cols=",".join(map(str, row.keys())) v_list=[] val=') VALUES(' for v in row.values(): if v== None: val=val+'NULL,' else: v_list.append(v) val=val+'%s,' val=val[:-1]+')' query="insert into stg_trn_data(" +cols + val mycursor.execute(query,v_list) connection.commit() return JsonResponse({"status": 201, "message": "Data Inserted"}) -
Get field is_active from model User
I have the model User with one of the fields is_active: class User(AbstractBaseUser, PermissionsMixin): objects = UserManager() is_active = models.BooleanField( _('active'), default=True, ) And I have the model Player with one of the fields user: class Player(models.Model): user = models.OneToOneField( 'users.User', null=True, on_delete=models.PROTECT, related_name='player', ) How can i get field is_active in PlayerAdmin model? user__is_active doesn't work -
TypeError: unsupported operand type(s) for -: 'IntegerField' and 'int'
I am struggling trying to sum/rest/multiply numbers on forms.py when they are different type, how to manage it? Thanks in advance MODELS.py myyear= models.IntegerField( db_column='XXX', choices=mychoices, default=str(year-1) ) period_from = dateitstart(myyear) UTILITIES.PY def dateitstart(myyear): return datetime.date(myyear -1, 10, 1) -
Making a biking class booking with Django
I am going to make my very first project using Django. I want to create a booking system where users can book biking classes according to timeslot availability. (Note: There will be three biking classes to choose from). I made the Database Schema (please see image below), but I am unsure how to create this in Django. I did my research online but could not find any similar logic in other projects. Any help would be truly appreciated! Thank you! Database Schema -
Django DTL flag for contact number is not working
I have a field with a named contact. and I am appending country code and flag. In the insert model, it is appending successfully. But in the Edit model, it is not appending as I am using DTL(for) to fetch data in text input. I have tried to put script after the text input with the script tag but still, it is not working. For edit, I have user DTL for loop so that I can display selected data into text input so that user can edit their data. Here is a screenshot of the Insert model. Insert model Here is a screenshot of the edit model where the flag is not working Edit model Here is my code. {% for vr in adduser.adduser.all %} <div class="modal fade" id="userEditModal-{{forloop.counter}}" tabindex="-1" role="dialog" aria-labelledby="largeModal" aria-hidden="true"> <div class="modal-dialog modal-lg modal-dialog-centered"> <div class="modal-content"> <form method="POST" action="{% url 'edituser' uid=vr.id bid=adduser.id %}" class="needs-validation" novalidate> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Edit Contact Data</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <!--Form Start--> <div class="form-row"> <div class="form-group col-md-6 smsForm"> <label for="contact1">SMS No.<span style="color:#ff0000">*</span></label> <input type="tel" class="form-control" name="smsno" id="smsno" value="{{vr.sms_no}}" placeholder="SMS No." pattern="^(00|\+)[1-9]{1}([0-9][\s]*){9,16}$" required /> <div class="valid-feedback">Valid.</div> <div class="invalid-feedback">Please enter valid contact no.</div> … -
Not able to get selected option in dropdown in update page of CRUD
I am doing CRUD and trying to do the update operation using foreign keys and serializers. the problem here is that I am struggling to retain the option of dropdown that I had saved I am using Django dropdown. for example I have categories as "fusion wear",but when I go to the edit page to try to edit it the categories doesnt show 'fusion wear' it shows '9-6wear' below are the serializers class CategoriesSerializer(serializers.ModelSerializer): class Meta: model = Categories fields = "__all__" extra_kwargs = {'category_name': {'required': False}} class ColorsSerializer(serializers.ModelSerializer): class Meta: model = Colors fields = "__all__" class POLLSerializer(serializers.ModelSerializer): # categories = serializers.StringRelatedField(many=False) # sub_categories = serializers.StringRelatedField(many=False) # color = serializers.StringRelatedField(many=False) # size = serializers.StringRelatedField(many=False) class Meta: model = Products fields = "__all__" class SizeSerializer(serializers.ModelSerializer): class Meta: model = Size fields = "__all__" class SUBCategoriesSerializer(serializers.ModelSerializer): class Meta: model = SUBCategories fields = "__all__" models class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) class Categories(models.Model): #made changes to category_name for null and blank category_name = models.CharField(max_length=20) category_description = models.CharField(max_length=20) isactive = … -
Django overwrites objects instead of creating a new one
I have some models - Model1, Model2, Model3 and Model4 - defined in models.py file: class Model1(models.Model): field1 = db.Charfield(max_length=10) class Model2(models.Model): field2 = db.Charfield(max_length=10) class Model3(models.Model): field3 = db.Charfield(max_length=10) class Model4(models.Model): m1 = db.ForeignKey('application.Model1', on_delete=models.CASCADE) m2 = db.ForeignKey('application.Model2', on_delete=models.CASCADE) m3 = db.ForeignKey('application.Model3', on_delete=models.CASCADE) class Meta: unique_together = (('m1', 'm2', 'm3'),) When I want to create new Model4 using Model1, Model2, Model3 objects from database Django overrides the Model4 contains the same Model1 and Model3 keys despite Model2 is completly different. for example: I have some Models4: with pk = 1: m1 = 1, m2 = 1, m3 = 1 with pk = 2: m1 = 1, m2 = 2, m3 = 2 When I want to add new Model4 with values: m1 = 1, m2 = 10, m3 = 1 Then Django does not create new one (however new primary key is created) but overrides the Model4 with pk = 1. What is going on here? Coud somebody help me? Thanks a lot in advance :D. -
Django get input radio select in a form
What I want, is a page where per user can be selected if they were either Present, Allowed Absent or Absent. I have managed to create a page where this is possible and can be submitted, see the image I attached. How the code works right now My problem is, I have no idea how I can get to the data I submitted. I used name={{user.id}} for the name of the radio buttons, but how can I now access this input in my view? I want to be able to do something different if Absent is selected for example, but I don't know how to do that. Here is my code: baksgewijs/mbaksgewijs_attendance.html <form action="" method=POST> {% csrf_token %} <div class="table-responsive fixed-length"> <table id = "userTable" class="table table-striped table-hover table-sm table-bordered"> <tbody> {% for user in users %} <tr> <td> {{ user }} <td> <div class="form-check"> <input class="form-check-input" type="radio" name={{user.id}} id="radio"> <label class="form-check-label" for="flexRadioDefault1"> Aanwezig </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name={{user.id}} id="radio"> <label class="form-check-label" for="flexRadioDefault2"> Afwezig </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name={{user.id}} id="radio"> <label class="form-check-label" for="flexRadioDefault2"> Geoorloofd afwezig </label> </div> </td> </tr> {% endfor %} </tbody> </table> </div> <br> <button class='btn btn-primary active' type="submit"> Update Peloton </button> … -
How to generate Django request object with ASGIHandler class programmatically
I have a Django project in which I have a function called some_func that uses request inside it. from fastapi import Depends from fastapi.security import HTTPBasicCredentials def foo(credentials: HTTPBasicCredentials = Depends(security),): # Need to generate a request object user = some_func() def some_func(request): x = request.GET.get('my_param') Unfortunately, I have no chance to edit the some_func function and the only solution is to generate an empty Django request object. I looked into the ASGIHandler class, method create_request, but I couldn't figure out how to set scope and body_file params. -
Running a Particular Function after a duration of 2 hours of occurance of an event in Django
Currently i am working on a Django project .Use case is when i add a device object in database,if it does not come online in the first 2 hours after addition then i need to delete that device object from database . i have written a function delete_device_from_db() which delete device if it not comes online.How to invoke this function exactly after 2 hours after the addition of device. In our project we are using celery to run background tasks and periodic tasks. what is the best way to solve this.can it be solved using celery? -
DisallowedHost at / Invalid HTTP_HOST header: [IP] ; You may need to add [IP] to ALLOWED_HOSTS
I want to deploy my Django app and I already used gunicorn, nginx and supervisor and stored on AWS EC2 Here is the snippet of my settings.py DEBUG = False ALLOWED_HOSTS = ['<my_ip>', '<my_ip>.ap-southeast-1.compute.amazonaws.com'] I have settings_prod.py and settings_dev.py settings_prod.py DEBUG = False ALLOWED_HOSTS = [ '<my_ip>', '<my_ip>.ap-southeast-1.compute.amazonaws.com'] From my wsgi.py from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'votingapp.settings_prod') I put the correct host address and it still got the same error: Exception Type: DisallowedHost Exception Value: Invalid HTTP_HOST header: '<ip>'. You may need to add '<ip>' to ALLOWED_HOSTS. The problem is it uses settings from settings_dev.py which is not my ideal sequence. I want the supervisor or settings_dev.py to allow my IP to host the site. Any help would be appreciated. -
How to connect Django API with Opencart API/Prestashop API
I have catalog on Django and I need to connect it with catalog on Opencart(or Prestashop). In other words, when I add product in Django it needed to appear on Opencart. I have created Django API where I can add users with permissions and they can add or delete products, I need to connect it somehow with Opencart API or database. What I should use to do that? Or maybe I need something else, instead using API? -
saved data not visible in CRUD using serializers and foreign keys
I am doing CRUD where I am using foreign keys and serializers as it is my task and I am new to serializers I am trying to update my data however the saved data of categories,sub_categories,color and size arent showing up isntead are showing up as blank as shown below below are all the serializers class CategoriesSerializer(serializers.ModelSerializer): class Meta: model = Categories fields = "__all__" extra_kwargs = {'category_name': {'required': False}} class ColorsSerializer(serializers.ModelSerializer): class Meta: model = Colors fields = "__all__" class POLLSerializer(serializers.ModelSerializer): # categories = serializers.StringRelatedField(many=False) # sub_categories = serializers.StringRelatedField(many=False) # color = serializers.StringRelatedField(many=False) # size = serializers.StringRelatedField(many=False) class Meta: model = Products fields = "__all__" class SizeSerializer(serializers.ModelSerializer): class Meta: model = Size fields = "__all__" class SUBCategoriesSerializer(serializers.ModelSerializer): class Meta: model = SUBCategories fields = "__all__" models class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) class Categories(models.Model): #made changes to category_name for null and blank category_name = models.CharField(max_length=20) category_description = models.CharField(max_length=20) isactive = models.BooleanField(default=True) def __str__(self): return self.category_name class Colors(models.Model): color_name = models.CharField(max_length=10) color_description = models.CharField(max_length=10) isactive = models.BooleanField(default=True) def … -
Gunicorn keeps timing out and bad gateway upon password request in django application
Yesterday I deployed a Django application on a Linode VPS using this Guide. All of the functionality of my app works as expected except password resetting does not work. i am using mailgun to reset passwords for the application. There is nothing wrong with mailgun as i have tried password resetting in local development server and it works fine. Here is what I have observed so for from my attempts at debugging it. When i request for a password reset for an existing user (email) in the application, the request ends up as a 502 Bad gateway request. But if i request for a non existing user email the app works fine. /reset_password successfully redirects to /reset_password_sent Here are logs from gunicorn. For this bad gateway error and the [CRITIAL] WORKER TIMEOUT error i found this and did try including the --timeout 120 in the /etc/systemd/system/gunicorn.service file When i tried that i get 504 Gateway Time-out i have also tried including the following in the nginx config but it keeps giving 504 Gateway Time-out error. server { keepalive_timeout 180s; send_timeout 180s; proxy_connect_timeout 180s; proxy_send_timeout 180s; proxy_read_timeout 180s; ...rest of the config } -
Can two Django projects share the same database?
I have been learning to deploy databases and Django apps on Azure, and I have several projects on there up and running. My question is, can multiple Django apps share a database? As in the apps are unrelated and will not be sharing information, I just don't want to spin up a new database for each project when realistically I will likely be the only one using it. Is this possible without overwriting other tables in the database? -
I'm trying to use channels for some WebSockets-related stuff, but it keeps loading and not showing any live streaming response when i reload web page
work Fine INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', ] Not Work INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'channels', ] Work Fine -> WSGI_APPLICATION = 'myproj.wsgi.application' Not Work -> ASGI_APPLICATION = 'myproj.asgi.application' -
Remove Type From values_list
Wanted to remove the guard from the query set. Guard is a many-to-many field in the table InstituteGate def delete(self, request): institute = self.request.query_params.get("institute", None) data = request.data queryset = InstituteGate.objects.filter( institute=institute, name=data["gate"]) for i in queryset: guards = i.guards.all().values_list('id', flat=True,) print(guards) if data["guard"] in guards: i.guards.remove(data["guard"]) return Response("Succesfully Removed Guard From gate", status=status.HTTP_200_OK) printing guard gives <QuerySet [UUID('dfca4bbf-e823-4888-af6b-7fc6438c697e'), UUID('62663459a-ff71-4f5e-86c6-36405b611859'), UUID('sd52sds-2825-43ac-91b2-3cccae48b4ab'), UUID('adadss55d-4a7d-4e31-850b-f5a55beb75ce')]> But I need <QuerySet [('dfca4bbf-e823-4888-af6b-7fc6438c697e'), ('62663459a-ff71-4f5e-86c6-36405b611859'), ('sd52sds-2825-43ac-91b2-3cccae48b4ab'), ('adadss55d-4a7d-4e31-850b-f5a55beb75ce')]> What to do?? -
how to display a specific searched word from a string in django?
I have developed the searched feature in Django using Q object, and get the result like this: what recommendations are you looking for? I searched using word recommendations and it displayed the whole object of the model. I am using this query for search feature in views.py: recommendations_searched_query = Report.objects.filter(Q(recommendations__icontains=query)) and template tags in html {{recommendations.recommendations|truncatewords:5}} What I want is: when I type word recommendations in the search field, the query should display the word recommendation from the string and 5 words before and 5 words after the searched word. you can guide me using this string: I want to test the search queries for recommendations in the Reports model -
Not able to Update CRUD data with foreign keys despite putting correct namings
I am doing CRUD data which has foreign keys and serializers(since I am told to use serializers instead of Forms),even though I have put the correct model and it's names in the product_edit page, the data is showing blank instead of thier saved data ,the wrong sub_category name is coming,this is how the edit page currently looks below are the models of my CRUD class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) class Categories(models.Model): #made changes to category_name for null and blank category_name = models.CharField(max_length=20) category_description = models.CharField(max_length=20) isactive = models.BooleanField(default=True) def __str__(self): return self.category_name class Colors(models.Model): color_name = models.CharField(max_length=10) color_description = models.CharField(max_length=10) isactive = models.BooleanField(default=True) def __str__(self): return self.color_name class Size(models.Model): size_name = models.CharField(max_length=10) size_description = models.CharField(max_length=20) isactive = models.BooleanField(default=True) def __str__(self): return self.size_name class SUBCategories(models.Model): category_name = models.ForeignKey(Categories, on_delete=models.CASCADE) sub_categories_name = models.CharField(max_length=20) sub_categories_description = models.CharField(max_length=20) isactive = models.BooleanField(default=True) def __str__(self): return self.sub_categories_name update function def update(request,id): if request.method == 'GET': print('GET',id) edit_products = SUBCategories.objects.filter(id=id).first() s= SUBCategoriesSerializer(edit_products) category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict, many=True) sub_category_dict = SUBCategories.objects.filter(isactive=True) sub_category = …