Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update django model objects from editable dash data-table
I want to update my models by an editable plotly dash-table (populated by a dataframe, himself populated by sqlconnection with models) in Django but I don't know how to :/ You will see my trials in code comments, but obviously, it doesn't work. Any solution for this pls? Here a class in exemple in models.py (same structure for each class): class interventions_acm1(models.Model): date_debut = models.CharField(max_length=30, null=True) date_fin = models.CharField(max_length=30, null=True) titre_intervention = models.CharField(max_length=30, null=True) cout = models.CharField(max_length=30, null=True) responsable_acm = models.CharField(max_length=30, null=True) entreprise_exec = models.CharField(max_length=30, null=True) descriptif = models.CharField(max_length=150, null=True) And views.py which contain table and connection with models: from django_plotly_dash import DjangoDash import dash_html_components as html import dash_table import dash_core_components as dcc from dash.dependencies import Input, Output, State import pandas as pd from django.db import connection from django.db.models import Q from django.shortcuts import render from django.http import HttpResponse from .models import interventions_acm1, interventions_acm4, interventions_acm5, interventions_acm9, interventions_acm10 #from sqlalchemy import create_engine # Create your views here. def interventions(request): #table_data = table_donnees() app = DjangoDash('Tableau_intervention') Magasin_interventions_real = request.GET.get('Magasin_interventions_real') Annee_mois_dispo_interv = request.GET.get('Annee_mois_dispo_interv') #if Magasin_data_query != '': query = str(interventions_acm1.objects.all().query) if Magasin_interventions_real == 'ACM1': query = str(interventions_acm1.objects.all().query) elif Magasin_interventions_real == 'ACM4': query = str(interventions_acm4.objects.all().query) elif Magasin_interventions_real == 'ACM5': query = str(interventions_acm5.objects.all().query) elif Magasin_interventions_real … -
AttributeError: module 'django.db.models' has no attribute 'ArrayField'
hola tengo un problema al intentar crear una coleccion de colecciones en django dice que no reconoce AttributeError: module 'django.db.models' has no attribute 'ArrayField' from django.db import models class Link(models.Model): source = models.IntegerField() target = models.IntegerField() label = models.CharField(max_length=200) class Node(models.Model): ide = models.IntegerField() name = models.CharField(max_length=200) x = models.IntegerField() y = models.IntegerField() class Root(models.Model): links = models.ArrayField(model_container=Link) nodes = models.ArrayField(model_container=Node) class Graph(models.Model): root = models.ArrayField(model_container = Root) -
Error 404 was reported in the django tutorial [closed]
https://docs.djangoproject.com/zh-hans/4.0/intro/tutorial01/ Djangos official documentation for creating a voting application enter image description here enter image description here enter image description here -
Django: TemplateSyntaxError at /category/2/
1. Summarize the problem I great custom tag. In file news_tags.py from django import template from news.models import Category register = template.Library() @register.simple_tag() def get_categories(): return Category.objects.all() I called the tag in the sidebar.html file {% load news_tags %} {% get_categories %} <div class="list-group"> {% for item in categories %} <a href="{% url 'category' item.pk %}" class="list-group-item list-group-item-action">{{ item.title }}</a> {% endfor %} </div> This my folder structure My Error: TemplateSyntaxError at /category/2/ 'news_tags' is not a registered tag library 2. Describe what you’ve tried I looked at this question. But there was an error in an unclosed quote I looked at this question. I write in settings.py TEMPLATES.options.context_processors 'mainsite.news.template_tags.news_tags',. But error No module named 'mainsite.news' -
Django Question: How can i submit a form with logged in user as default?
After you sign up, you are prompted to the login page, and after you login, you are redirected to another page that contains a form used for gathering additional information about the new user. The problem is that the form doesn't submit if i don't specify the {{form.user}} instance in the html file. Probably because the user_id is not recognized by default. When i specify it, the form let me chooses from already existing users, and i would like it to go with the logged in user by default. models class AdditionalInfoModel(models.Model): objects = None skill_choices = (('Beginner', 'BEGINNER'), ('Intermediate', 'INTERMEDIATE'), ('Expert', 'EXPERT')) user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=30, blank=True) assumed_technical_ski_level = models.CharField(max_length=30, choices=skill_choices) years_of_experience = models.PositiveIntegerField(blank=True) money_to_spend = models.PositiveIntegerField(blank=True) def __str__(self): return self.user.username the log in and sign up are done using standard django models -
TypeError: list indices must be integers or slices, not dict
I'm trying to return all the JSON data from the payload but its giving an error as TypeError: list indices must be integers or slices, not dict. When I print(request.data) it's just returning all the JSON data but when I do the for loop its giving the error Here, what I tried views.py: @api_view(['POST']) def SaveUserResponse(request): if request.method == 'POST': for i in request.data: print(request.data) auditorid =request.data[i]['AuditorId'] print('SaveUserResponse auditorid---', auditorid) ticketid =request.data[i]['TicketId'] qid = request.data[i]['QId'] answer = request.data[i]['Answer'] sid = request.data[i]['SID'] print('sid--', sid) cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_SaveAuditResponses] @auditorid=%s,@ticketid=%s,@qid=%s,@answer=%s,@sid=%s', (auditorid,ticketid,qid,answer, sid,)) result_st = cursor.fetchall() for row in result_st: print('sp_SaveAuditResponse', row[0]) return Response(row[0]) return sid JSON payload: [ 0: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111111", QId: 1, Answer: "2", SID: 3982,…} 1: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111111", QId: 2, Answer: "2", SID: 3982,…} 2: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111111", QId: 3, Answer: "2", SID: 3982,…} 3: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111111", QId: 4, Answer: "2", SID: 3982,…} 4: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111111", QId: 5, Answer: "5", SID: 3982,…} 5: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111111", QId: 6, Answer: "5", SID: 3982,…} 6: {AuditorId: 122, … -
Django dictionary for annotations works or not depending on the order of the most complex annotation and/or the aliases of the other annotations
So I came across this issue described in the title of this post. I have this dynamically created dictionary: dict= {'sale_qty': Sum('sale_qty'), 'sales_override': Sum(F('sales_override')), 'colab_ventas': Sum(F('colab_ventas')), 'Historia Ajustada': Sum(Case(When(sales_override=None, then=F('sale_qty')),When(sales_override__gte=0, then=F('sales_override'))))} This is the query: Venta.objects.values('item').annotate(**dict) and when I try to run it, it fails with error: Exception Type: FieldError Exception Value: Cannot compute Sum('<Case: CASE WHEN <Q: (AND: ('sales_override', None))> THEN F(sale_qty), WHEN <Q: (AND: ('sales_override__gte', 0))> THEN F(sales_override), ELSE Value(None)>'): '<Case: CASE WHEN <Q: (AND: ('sales_override', None))> THEN F(sale_qty), WHEN <Q: (AND: ('sales_override__gte', 0))> THEN F(sales_override), ELSE Value(None)>' is an aggregate BUT if I change the order of the elements in the dictionary moving the complex annotation 'Historia Ajustada' to the beggining it works just fine: dict= {'Historia Ajustada': Sum(Case(When(sales_override=None, then=F('sale_qty')),When(sales_override__gte=0, then=F('sales_override')))),'sale_qty': Sum('sale_qty'), 'sales_override': Sum(F('sales_override')), 'colab_ventas': Sum(F('colab_ventas')) } It also works fine if I keep the original order of the dictionary and change the aliases of the simple annotations like this (for example adding a '1' to the alias): dict= {'sale_qty1': Sum('sale_qty'), 'sales_override1': Sum(F('sales_override')), 'colab_ventas1': Sum(F('colab_ventas')), 'Historia Ajustada': Sum(Case(When(sales_override=None, then=F('sale_qty')),When(sales_override__gte=0, then=F('sales_override'))))} What could be the cause of this ? Is this a django bug or expected behaviour? I have to give special treatment to some parts of the … -
Save data into a postgres db with Serializer
My problem is that I am trying to save into a postgres db some arrays, but it seems that it does not work, since the db is empty. My models.py is as follows: from django.db import models from django.contrib.postgres.fields import ArrayField from django.contrib.auth import get_user_model CustomUser = get_user_model() class Event(models.Model): user_id_event = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) dr_notice_period = models.IntegerField(blank=True, null=True) dr_duration = models.IntegerField(blank=True, null=True) dr_request = models.FloatField(blank=True, null=True) class Result(models.Model): event_id_result = models.OneToOneField(Event, on_delete=models.CASCADE, null=True) hvac_flex = ArrayField(models.FloatField(blank=True, null=True)) dhw_flex = ArrayField(models.FloatField(blank=True, null=True)) lights_flex = ArrayField(models.FloatField(blank=True, null=True)) My serializers.py is as follows: from rest_framework import serializers from vpp_optimization.models import Event, Result class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ('__all__') class ResultSerializer(serializers.ModelSerializer): class Meta: model = Result fields = ('__all__') And my views.py as follows: from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework import status from vpp_optimization.importer import DR_event_import_data from vpp_optimization.utils import optimization_solution from vpp_optimization.serializers import EventSerializer, ResultSerializer from vpp_optimization.models import Event, Result @api_view(['POST']) @permission_classes([IsAuthenticated,]) def event(request): serializer = EventSerializer(data=request.data) if serializer.is_valid(): serializer.save(user_id_event=request.user) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET']) def optimization(request): last_event = Event.objects.last() if not last_event: return Response({"res": "Object Event does not exists"}, status=status.HTTP_400_BAD_REQUEST) … -
Django FieldError at /admin/ in Multidropdown Filter
In the django i am geeting this error, my models.py class User(MasterDataBaseModel): user_name = models.CharField(max_length=255,verbose_name=_("username")) gender = models.ForeignKey(Gender, null=True, blank=True, on_delete=models.CASCADE, verbose_name=_("Gender")) the admin.py class Useradmin(DuplicateMixin, MasterDataBaseAdmin): form = forms.UserForm search_fields = ["user_name","Gender"] ordering = ["user_name"] list_filter = [ "users_name", ("Gender",MultiSelectDropdownFilter), ] list_display = [ "user_name", "Gender",] getting this error ,FieldError at /admin/registration/user/ -
Store datapoints persistently before writing to database
I have a Django app that receives sensor data. This data is then processed and written to influxDB using the influxdb-client-python library. I would like to write the data in an asynchronous manner and thus return a response to the producer of the data before it is actually written to the database. However, once I send this response I can no longer afford to lose this data. Since I can never be sure that the server will in fact be able to write the data to influxDB, I was thinking about first writing it to a file and returning a response after this is successful (similar to a WAL). This introduces new problems like making sure the WAL is actually written to a file and most importantly, making sure it is thread-safe since the server may be handling multiple requests concurrently. Is there any better way of doing this, maybe built-in in Django? -
Django for React Freamework setup
code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: ccalendar@0.1.0 npm ERR! Found: react@18.0.0 npm ERR! node_modules/react npm ERR! react@"^18.0.0" from the root project npm ERR! npm ERR! Could not resolve dependency: npm ERR! peer react@"<18.0.0" from @testing-library/react@12.1.5 npm ERR! node_modules/@testing-library/react npm ERR! @testing-library/react@"^12.0.0" from the root project npm ERR! npm ERR! Fix the upstream dependency conflict, or retry npm ERR! this command with --force, or --legacy-peer-deps npm ERR! to accept an incorrect (and potentially broken) dependency resolution. npm ERR! npm ERR! See /Users/sahin/.npm/eresolve-report.txt for a full report. npm ERR! A complete log of this run can be found in: npm ERR! /Users/sahin/.npm/_logs/2022-04-12T12_34_08_137Z-debug-0.log npm install --no-audit --save @testing-library/jest-dom@^5.14.1 @testing-library/react@^12.0.0 @testing-library/user-event@^13.2.1 web-vitals@^2.1.0 failed (env) sahin@Sahin-MacBook-Pro-2 CAlendar % npm create-react-app ccalendar Unknown command: "create-react-app" -
How to get event from client socket and sent to django channels
I need to get info from websocket wss://ws.binotel.com:9002 routing.py websocket_urlpatterns = [ re_path(r'wss://ws.binotel.com:9002', BinotelCallsConsumer.as_asgi()), ] asgi.py application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ), }) But it dosnt connect to this socket -
Django - showing cdn npm gantt chart in template
I'm using a npm package called svelte-gantt via this cdn here: npm cdn. However I can't for the life of me get the chart to show in the template, I can't find an example of it being used with django so I'm not sure if it's possible. What am I doing wrong here for it not to show up? How can I use the package & gantt chart in my django template? {% extends "home/base.html" %} {% block content %} <style> #example-gantt { flex-grow: 1; overflow: auto; height: 600px; width: 100px; } .container { display: flex; overflow: auto; flex: 1; } </style> <div class="container"> <div id="example-gantt"></div> </div> <script src="https://cdn.jsdelivr.net/npm/svelte-gantt@4.0.3-beta/index.min.js"></script> <script> var options = {}; var gantt = new SvelteGantt({ // target a DOM element target: document.getElementById('example-gantt'), // svelte-gantt options props: options }); </script> {% endblock content %} -
Add Multuple Field django In admin Panel
How can I add please icons in Admin panel for exemple when I click to add icons ,it duplicate model Field . the Field is not related to forgien table . enter image description here -
Confirm Action inside JS success call - cancel button also submitting form
When a user clicks on submit button, I want to show a confirm dialog with a count of records that would be affected. To get the count, I am calling the related url inside ajax and in success am trying to confirm from user. But, in the confirmation dialog box, when user clicks on cancel also, the form is getting submitted successfully. $(document).ready(function(){ $('form').submit(function(e) { // e.preventDefault(); const a= $(id_a).val(); const b = $(id_b).val(); const c = $(id_c).val(); const d = $(id_d).val() $.ajax({ type: "GET", url: "/myURL", data: { 'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(), 'a':a, 'b':b, 'c':c, 'd':d }, success: function (data) { if (confirm(`${data.result} records will get affected. Do you want to continue?`)){ $('form#id_save').submit(); } else { e.preventDefault() } }); }) }) -
How to get the count of fields that are either None ot empty in a row using ORM Django?
I have a model, class personal_profile(models.Model): custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) picture = models.ImageField(default='pro.png', upload_to='profile_image', blank=True) designation = models.CharField(max_length=255, blank=True, null=True) gender = models.CharField(max_length=255, blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) language = models.CharField(max_length=255, blank=True, null=True) linkedin_url = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return str(self.pk) I want to get the number of field's count which are either None or "". personal_profile.objects.get(custom_user=some_user_id) By the open query, I can get the queryset of that specific user. Now that is a way to get the count of empty or None fields in database. Thanks -
Django - tabularinline in a forms in template
I have an votes app (question and choice). In admin i can use TabularInline to see for every question the fiedls choice (default 3 fields) and in admin i can set the name of the question, poster and choice for that question and i can create question with choices and from template i can vote etc. But I don't know how to make a form with exact mechanism to use in template where to set the name, poster and most important the choices for that question with the mecanism to add another choice like in admin area. What i try in the form is this class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class creareSondajForm(ModelForm): class Meta: model = Question fields = [ 'question_text', 'poster' ] inlines = [ChoiceInline] but in template it show only the input for name of the question and poster not the input where to set the choice. Please help me. Thank you! Below my settings. models.py class Question(models.Model): question_text = models.CharField(max_length=200, verbose_name='Intrebare') poster = models.ImageField ( upload_to ='sondaj/', default='sondaj/poster_sondaj_pl.jpg', verbose_name='Poster (120px * 96px)') pub_date = models.DateTimeField('publicat la:') def __str__(self): return self.question_text #pentru a redimensiona rezolutia posterului incarcat def save(self, *args, **kawrgs): super().save(*args, **kawrgs) img = … -
Django: end_time = models.TimeField. Is there a way to subtract minutes from this field?
I am trying to automatically subtract 60s or 1 minute from an end_time input by the user. Is there a way to do this? I am using Django v3.2. model.py end_time = models.TimeField(auto_now_add=False, blank=True) views.py def post(self, request): booking_form = BookingForm(data=request.POST) if booking_form.is_valid(): booking = booking_form.save(commit=False) booking.user = request.user if Booking.objects.filter( table=booking.table, date=booking.date, start_time=booking.start_time, approved=booking.approved is True ).exists(): return render(request, '/',) else: booking.save() return render(request, '/',) -
django modeltranslate default language duplicate value
my model: class DoctorSpeciality(BaseModel): name = models.CharField(max_length=255, unique=True, db_index=True) class Meta: db_table = 'doctor_specialities' When i am trying to translate this model, django modeltranslation creates two fields name_de, name_en. But i also have name field, name and name_de have same value. Is it possible not to create default language column into database to prevent duplicated value ? -
How to display a generated image stored in memory with django?
I am a beginner with django. I am trying to display an image that is stored in a variable. (I am using PIL for the image generation). This variable is then passed to the html page concerned. However I can't display this image because Django expects a path for this image which is stored in memory and not saved in a file. Is there a way to display an image that is stored in memory? Here is an example of code def img_generator(parm1,parm2,parm3): ... #image generation stuff return generated_image #somewhere else in the code my_img = img_generator(8,4,8) The image is transmitted as follows: def results(request): return render(request, "html_page_to_display.html", context={'var1':var1, .#other vars .#other vars 'my_img':my_img, # my image I want to display }) And finally, the image is displayed via the following html tag: <img src=" {{ my_img }}" /> I am definitely doing it the wrong way. Could you help me to solve this problem ? Here are 2 logs describing the error : Not Found: /index/home/<PIL.Image.Image image mode=RGBA size=234x305 at 0x174792017B0> [12/Apr/2022 13:36:17] "GET /index/home/%3CPIL.Image.Image%20image%20mode=RGBA%20size=234x305%20at%200x174792017B0%3E HTTP/1.1" 404 4072 -
Django - how to pass objects instance data from one view to the next
so I'm making digital schoolregister as a portfolio project. Here I have one view: for the teacher, with list of students in a class and next to them are their grades. I wanted to make each grade as hyperlink so after clicking one - it can be edited, but my code doesn't pass this grade data to the next view. Here's my code: views.py @login_required def class_detail(request): school_class = get_object_or_404(SchoolClass, id=1) semesters = school_class.school_year.semester_set.all() students = school_class.students.all() grades_1_sem = [] grades_2_sem = [] subject = Subject.objects.get(id=1) for student in students: grades_1_sem.append(student.grade_set.filter(school_year=school_class.school_year, semester=Semester.objects.get(number=1))) grades_2_sem.append(student.grade_set.filter(school_year=school_class.school_year, semester=Semester.objects.get(number=2))) students_grades_1_sem = list(zip(students, grades_1_sem)) students_grades_2_sem = list(zip(students, grades_2_sem)) return render(request, 'schoolregister/nauczyciel/klasa.html', { 'school_class': school_class, 'students': students, 'grades': grades, 'subject': subject, 'students_grades_1_sem': students_grades_1_sem, 'students_grades_2_sem': students_grades_2_sem, }) def edit_grade(request): if request.method == 'POST': grade_to_edit = GradeToEdit(request.POST) if grade_to_edit.is_valid(): grade_to_edit.save() return HttpResponseRedirect('') else: return HttpResponse("Error.") else: grade_to_edit = GradeToEdit() return render(request, 'schoolregister/edit_grade.html', {'grade_to_edit': grade_to_edit,}) forms.py class GradeToEdit(forms.ModelForm): class Meta: model = Grade fields = ('grade', 'school_year', 'semester', 'subject', 'student', 'description') urls.py urlpatterns = [ path('nauczyciel/<int:school_class_id>/<int:subject_id>/', views.class_detail, name='class_detail'), path('edit_grade/', views.edit_grade, name='edit_grade'), ] Here's the code with a href tag that should go to next view, and pass data, but it doesn't pass data for Grade instance: klasa.html {% for semester … -
Can someone suggest me how to use React ,Django and GraphQL
I am a React.js developer, Learning Django as backend and GraphQL. Stuck with fetching data from the backend using Graphql -
OSError: cannot load library 'gobject-2.0-0' M1-Cheap
import weasyprint Traceback (most recent call last): File "", line 1, in File "/Applications/MAMP/htdocs/django/virtualenv/lib/python3.10/site-packages/weasyprint/init.py", line 325, in from .css import preprocess_stylesheet # noqa isort:skip File "/Applications/MAMP/htdocs/django/virtualenv/lib/python3.10/site-packages/weasyprint/css/init.py", line 27, in from . import computed_values, counters, media_queries File "/Applications/MAMP/htdocs/django/virtualenv/lib/python3.10/site-packages/weasyprint/css/computed_values.py", line 16, in from ..text.ffi import ffi, pango, units_to_double File "/Applications/MAMP/htdocs/django/virtualenv/lib/python3.10/site-packages/weasyprint/text/ffi.py", line 404, in gobject = _dlopen( File "/Applications/MAMP/htdocs/django/virtualenv/lib/python3.10/site-packages/weasyprint/text/ffi.py", line 391, in _dlopen return ffi.dlopen(names[0]) # pragma: no cover File "/Applications/MAMP/htdocs/django/virtualenv/lib/python3.10/site-packages/cffi/api.py", line 150, in dlopen lib, function_cache = _make_ffi_library(self, name, flags) File "/Applications/MAMP/htdocs/django/virtualenv/lib/python3.10/site-packages/cffi/api.py", line 832, in _make_ffi_library backendlib = _load_backend_lib(backend, libname, flags) File "/Applications/MAMP/htdocs/django/virtualenv/lib/python3.10/site-packages/cffi/api.py", line 827, in _load_backend_lib raise OSError(msg) OSError: cannot load library 'gobject-2.0-0': dlopen(gobject-2.0-0, 2): image not found. Additionally, ctypes.util.find_library() did not manage to locate a library called 'gobject-2.0-0' -
MultiValueDictKeyError when passing empty file
In my website uploading picture is not compulsory, Therefore when left empty I get MultiValueDictKeyError But if i pass an image is dont get an error. Am I missing some thing?? Thanks in advance.... views.py if request.method == "POST": FirstName = request.POST['FirstName'] LastName = request.POST['LastName'] image = request.FILES['image'] #This one age = request.POST['age'] gender = request.POST['gender'] address = request.POST['address'] PhoneNumber = request.POST['PhoneNumber'] EmailAddress = request.POST['EmailAddress'] Password = request.POST['Password'] RepeatPassword = request.POST['RepeatPassword'] BloodGroup = request.POST['BloodGroup'] try: if Password == RepeatPassword: Patient.objects.create(FirstName=FirstName, LastName=LastName, image=image, age=age, gender=gender, address=address, PhoneNumber=PhoneNumber, EmailAddress=EmailAddress, BloodGroup=BloodGroup) return redirect('login') else: messages.success( request, ("Passwords do not match. Please try again")) except Exception as e: messages.success( request, ("This email already exists. Try again with another email or recover your account")) return render(request, 'signup.html') HTML <div class="input-div one"> <div class="i"> <ion-icon name="image-sharp"></ion-icon> </div> <div class="div"> <h5>Photo</h5> <input type="file" class="input" name="image"> </div> </div> -
django display the records inside folders
So, here i have records on my django website where i list the records so all theses records belong to different categories currently i have my them displayed like this but i want them to be listed inside the folders named after categories that means the all the records should be grouped based on categories and should reside inside the folders that belongs that particular folder. views.py class RecordListAPIView(ListAPIView): serializer_class = "" permission_classes = "" queryset = Model.objects.all() ordering = "" ordering_param = "" ordering_fields = ( ) def get_total_queryset(self): if self.request.user: return Model.objects_with_cat.all() return Model.objects.all()