Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get queryset data in django which picked from two range date calender forms (date_from - date_to)?
i've tried to follow this tutorial: https://www.youtube.com/watch?v=04L0BbAcCpQ&t=5133s (minutes: 2:10:27) as creator said, to access the date directly, we need to code double underscore as "created__date". That's because mentioned in django documentation perfectly the same way. this still didn't get me result as the creator had. Meanwhile, when i disabled my filter (qs = Sale.objects.filter(date=date_from) in views.py) and print it as object it's worked. Also when i moved queryset code a head from if block code, it's print perfectly compiled from qs = Sale.objects.all() and gave me result all of 3 data of it. #here is the views.py: from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Sale from .forms import SalesSearchForm # from django.views.generic.list import ListView # Create your views here. def home_view(request): form = SalesSearchForm(request.POST or None) if request.method == 'POST': date_from = request.POST.get('date_from') date_to = request.POST.get('date_to') chart_type = request.POST.get('chart_type') print(date_from, date_to, chart_type) # qs = Sale.objects.all() #atau bisa diganti dengan filter tertentu untuk seleksi data yang di inginkan: qs = Sale.objects.filter(created__date=date_from) obj = Sale.objects.get(id=2) print(qs) print(obj) # hello = 'hello world from sales/views.py' context = { # 'hello': hello, 'form': form, } return render(request, 'sales/home.html', context) here is the model.py (pay attention at Class Sale): … -
how am i able to add paginator to queryset?
selectors.py def ultimate_product_selector(request) -> Product: q = request.query_params.get('q', None) c = request.query_params.get('category', None) f = request.query_params.get('filter', None) pp = request.query_params.get('per_page', 20) p = request.query_params.get('page', 1) o = request.query_params.get('order', None) query = Product.objects.all() if c: query = query.filter(category__headline__in=category_list(c)) if q: query = query.filter(Q(headline__icontains=q) | Q(tag__icontains=q)).distinct() if f: # mdzime = %2C # ori wertili = %3A # wermil mdzime = %3B filter_and_option = f.split(";") for fo in filter_and_option: split_fo = fo.split(":") option_list = split_fo[1].split(",") query = query.filter(barcode__in=Barcode.objects.filter(filteroption__headline__in=option_list, filteroption__filter__headline=split_fo[0].lower())) if p: paginator_per_page = Paginator(query, pp) paginator_page = Paginator(query, p) im trying to add paginator to show next products at next pages if request.query_params is None: query = Product.objects.none() return query all i`m trying to do is create url like 0.0.0.0?page=1&per_page=5 to show next products with paginator. when i try to put -
Is there any way in which I can store a object(probably a huge size matrix) across the views in Django?
What I am doing is uploading a zip matrix file(hda5 format) and storing its path in the database. Now after uploading it ,I unzip the file and I want to store the anndata object across the views now. "Anndata format An annotated data matrix. AnnData stores a data matrix X together with annotations of observations obs ( obsm , obsp ), variables var ( varm , varp ), and unstructured annotations uns ". Now I want the reading of hda5 file to be happen only once ...and after that it should be persistent across the session. So , basically my question comes down to the point - that is there any way we can store a complex object (in my case anndata) across the views for a particular session in DJANGO? -
how to set autocomplete on django foreignkey field?
I have a model in my project: class Package(models.Model): rt_number=ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=ForeignKey(Treatment, on_delete=CASCADE) patient_type=ForeignKey(PatientType, on_delete=CASCADE) date_of_admission=models.DateField(default=None) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) The rt_number and diagnosis fields have multiple options and are inevitably going to grow in the coming times, making it difficult for the users to find their desired option in the dropdown. Is there a possible way for the users to sort or filter through the options wherein they type some characters of their target option and the option shows up? I tried this in the forms.py: class PackageForm(ModelForm): class Meta: model=Package fields='__all__' widgets={ "rt_number" : forms.Select(attrs={"autocomplete":"on"}) } But it doesn't work despite the attribute showing in the HTML. Please help with suggestions. -
How to filter on nested serializer in Django rest framework?
I want to get all user data which logged in user-id is same with userhascompany user id. These are UserHasCompany Mode, UserListSerializer, api.py model.py class UserHasComapny(models.Model): company = models.ForeignKey(CompanyDetail, related_name='user_has_company_company', on_delete=models.CASCADE, null=True, unique=False) user = models.OneToOneField(User, related_name='user_has_company_user', on_delete=models.CASCADE, null=True, unique=False) department = models.ForeignKey(Department,related_name='user_has_company_department', on_delete=models.CASCADE, null=True, unique=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = "user_has_company" default_permissions = () serializer.py class UserListSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'last_login', 'is_superuser', 'username', 'first_name', 'last_name', 'email', 'is_staff', 'is_active', 'date_joined', 'status', 'department', 'contact', 'groups') related_fields = ['status', 'user_has_company_user', 'user_detail', 'groups'] # depth = 1 status = serializers.BooleanField(source='status.status') contact = serializers.CharField(source='user_detail.contact') department = UserHasCompanySerializer(source='user_has_company_user',read_only=True) api.py class UserList(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserListSerializer def get(self, request, format=None): users = User.objects.all() serializer = UserListSerializer(users, many=True) return Response(serializer.data) -
Django CORS with credentials issue on
I am having a CORS issue and I need a second opinion on how to approach this. For starters. I have a Firebase hosted website let's say website.com I have my services at GKE let's say services.com Backend is Django and to login it sets a cookie called auth_token. I use Django-Cors and my settings are such DEBUG = False SESSION_COOKIE_SAMESITE = None # response header set-cookie:samesite=lax Default: 'Lax' # CSRF_COOKIE_SAMESITE = None CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ['https://website.com'] CSRF_TRUSTED_ORIGINS = ['https://website.com'] in the front-end I request resources like this const headers = new Headers(); headers.append('Accept', 'application/json'); let requestParams = { method, mode: 'cors', // redirect: 'follow', credentials: 'include', headers, }; Finally, a) I have added corsheaders to apps and middleware so not the issue b) when I try to request Authenticated resources I am getting a 401 and no CORS issues which tells me it's just setting the cookie -
Django rest framework DELETE request blocked [closed]
I have a frontend using react and a backend using django rest framework. When I make a DELETE request from react using fetch - I keep getting this error - Access to fetch at 'http://localhost:8000/notes' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. DELETE http://localhost:8000/notes net::ERR_FAILED I am able to make POST and GET requests without problems. My django settings.py has this - CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', "OPTIONS" 'POST', 'PUT', ] My react fetching code - const requestOptions = { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, withCredentials: true, crossorigin: true, }; fetch(`http://localhost:8000/notes`, requestOptions) .then(response => response.json()) .then(data => {}); My django code (this is inside a class extending APIView) - def delete(self, request, format=None): note = Note.objects.get(12) #the 12th note note.delete() return Response(status=status.HTTP_204_NO_CONTENT) How can I correct this? Please help. Thank you! -
Using ajax with django framework to reload div and display json
here is the web page I am currently working on: web site As you can see I have a config panel and what I would like to do is when I click on the 'Générer' button, the inverted tree appears and shows my configurations. For this I use django with ajax: ajax code The url in the code send to this function in views.py: compute function And from the json which is created, I would like to use it in my html page like that for instance: exemple -
How can I create a single form from multiple tables in Django and perform create and update operation on all the tables by using the form created?
This is my models.py and I need a single form for all the tables to perform CRUD operations and also, please tell me what should I read in the documentation for this. models.py from django.db import models # Create your models here. class Department(models.Model): name = models.CharField(max_length=50) class Designation(models.Model): name = models.CharField(max_length=50) class Country(models.Model): name = models.CharField(max_length=50) class State(models.Model): name = models.CharField(max_length=50) country_id = models.ForeignKey(Country, on_delete=models.CASCADE) class City(models.Model): name = models.CharField(max_length=50) state_id = models.ForeignKey(State, on_delete=models.CASCADE) class Employee(models.Model): emp_id = models.IntegerField(primary_key=True) emp_name = models.CharField(max_length=50) salary = models.IntegerField() joining_date = models.DateField() dept_id = models.ForeignKey(Department, on_delete=models.CASCADE) designation_id = models.ForeignKey(Designation, on_delete=models.CASCADE) city_id = models.ForeignKey(City, on_delete=models.CASCADE) -
Query multiple models in Graphene Django
I have multiple models in Django named model1, model2, model3. Each model has the same fields and the field id is the primary key. I want to query this database using GraphQL. The query structure should be like below. query{ pod(model: "model1",id: "1") { id data1 data2 } } This should get me the object for id 1 from model 1. How can I do this in Django using Graphene ? -
how to embad an advance domain name search in django
I working on a web-hosting project where i need to integrate a domain name search for clients to search for a domain. using whois or PyNamecheap, i can check if domain is available or not. but I want something more like namecheap domain search page to have Suggested Results and show combination of other extensions(top-level-domains) in my Results too. -
Django Aggregate Between Timezone Aware Fields
I want to find the average time between two dates - 'created_date' and 'modified_date'. Both are DateTimeField and values are timezone aware. example.created_date = datetime.datetime.now(tz=timezone.utc) example.save() I ran the below query: avg_change = Color.objects.filter(is_published=True).aggregate(avg_score=Avg(F('modified_date') - F('created_date'))) I got the error below. if dt.tzinfo is not None: AttributeError: 'decimal.Decimal' object has no attribute 'tzinfo' I'm on Python3.6/Django2.2/mysql 5.7. I'm not sure if I need to change the values to naive and then aggregate. What am I missing? Any viable route to approach this as I am not good with raw SQL. -
Django JWT Auth and Vue: How to check if user is logged in in Vue?
I have my backend in Django and front in Vue. A user performes login in Vue and via a POST request the creds are sent to a Django JWT login endpoint. This endpoint returns a token which is set in localStorage. Then I want to check in Vue that the user is logged in. For that another endpoint in Django exists. However, it always returns "AnonymUser". I cannot get how to set this check. Django: My settings.py JWT_AUTH = { 'JWT_ALLOW_REFRESH': True, 'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1), 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7), } My urls.py path('check-auth', views.check_if_logged_in, name="check-auth"), # check auth path('auth/obtain_token', obtain_jwt_token), # obtain token path('auth/refresh_token', refresh_jwt_token), My views.py # Login Check @csrf_exempt def check_if_logged_in(request): authentication_class = (JSONWebTokenAuthentication,) permission_classes = (IsAuthenticated,) print(request.user) # returns AnonymUser check = None if request.user.is_authenticated: check = True else: check = False print(check) # returns False return HttpResponse(f"<html><body>{check}</body></html>") Vue obtainToken function obtainToken(){ var that = this; fetch(this.endpoints.obtainJWT, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ username: that.django.username, password: that.django.password }) }).then(response => response.json() ).then(function(response) { console.log('auth', response); # get token that.updateToken(response.token); # update localStorage that.checkAuthData(); #check auth }); }, checkAuth function checkAuthData: function() { var that = this; fetch('http://localhost:8000/check-auth', { method: 'POST', headers: { 'Accept': 'application/json', … -
after click a button, the checked check box in a list should disappear
I have a web app, using Django as backend and normal HTML as frontend. In a HTML page, there's a checkbox list. After some checkboxes are checked and a button is clicked, the checked checkboxes should disappear and other checkboxes should auto fill the blank. How could I do that in JavaScript? <label class="radio-inline"> <div>&emsp;&emsp;<input type="checkbox" onclick="toggle(this)" name="optradio" value="notspecific"> select all courses below.</div> <br> {% for course in query_results_course %} <input type="checkbox" name="course" value="{{course}}" >&nbsp;<a href="{% url 'bms:View_by_Course_list_2' course_for_select=course %}" onclick="">{{course}}</a> <br>{% endfor %} </label> <button class="button" type="button" onclick="send_disappear()">send_disappear</button> <script> function send_disappear() { } </script> -
Django how to pass user object in class based view pagenation?
The default class based view pagination returning all object. I have an my account page for my each individual user where I need to show pagination number. By default pagination is same for all user. Let you explain little bit. If user A have 10 items and I listed 2 items per page then user A will be see total 5 page in his account which is fine but user B haven't any items and he is currently seeing only pagination number like page1,page2,page3... in his account because the current pagination returning all items from database. here is my code: views.py class BlogMyAccount(ListView): paginate_by = 10 model = Blog template_name = 'blog/my-account.html' ordering = ['-id'] #html {% for blog in object_list %} {% if user.id == blog.author.id %} ....my code {% endif %} {% endfor %} <!---pagination code----> <ul class="pagination justify-content-center mb-4"> {% if page_obj.has_previous %} <li class="page-item"><a class="page-link" href="?page=1">First Page</a></li> <li class="page-item"><a class="page-link" href="?page={{ page_obj.previous_page_number }}">← Back</a></li> {% endif %} {% if page_obj.has_next %} <li class="page-item"><a class="page-link" href="?page={{ page_obj.next_page_number }}">Next Page →</a></li> {% endif %} {% for i in paginator.page_range %} {% if page_obj.number == i %} <li class="page-item"><a class="page-link" href="#!">{{ i }}</a></li> {% elif i > page_obj.number|add:'-3' and … -
Daphne not accepting websocket connections
I am trying to use daphne in django project to handle the websocket connections. I have installed daphne and it seems to be running. However, I am unable to send any websocket connection request. This is my daphne.service file: [Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=root WorkingDirectory=/home/django/AysleServer/src ExecStart=/home/django/AysleServer/MyEnv/bin/python /home/django/AysleServer/MyEnv/bin/daphne -e ssl:8001:privateKey=/etc/letsencrypt/live/djangoadmin.aysle.tech/privk> Restart=on-failure [Install] WantedBy=multi-user.target On checking the logs of Daphne it shows this: Started WebSocket Daphne Service. Starting server at ssl:8001:privateKey=/etc/letsencrypt/live/djangoadmin.aysle.tech/privk...> HTTP/2 support not enabled (install the http2 and tls Twisted extras) Configuring endpoint ssl:8001:privateKey=/etc/letsencrypt/live/djangoadmin.aysle.tech/pri...> Listening on TCP address 0.0.0.0:8001 I thought that http2 and tls were causing the issue so tried to install them in my virtual environment using the command: pip install -U 'Twisted[tls,http2]' But they were already present as shown below: Requirement already satisfied: Twisted[http2,tls] in /usr/lib/python3/dist-packages (18.9.0) Requirement already satisfied: idna!=2.3,>=0.6 in /usr/lib/python3/dist-packages (from Twisted[http2,tls]) (2.8) Requirement already satisfied: pyopenssl>=16.0.0 in /usr/lib/python3/dist-packages (from Twisted[http2,tls]) (19.0.0) Requirement already satisfied: service_identity in /usr/lib/python3/dist-packages (from Twisted[http2,tls]) (18.1.0) Requirement already satisfied: h2<4.0,>=3.0 in /usr/local/lib/python3.8/dist-packages (from Twisted[http2,tls]) (3.2.0) Requirement already satisfied: priority<2.0,>=1.1.0 in /usr/local/lib/python3.8/dist-packages (from Twisted[http2,tls]) (1.3.0) Requirement already satisfied: hpack<4,>=3.0 in /usr/local/lib/python3.8/dist-packages (from h2<4.0,>=3.0->Twisted[http2,tls]) (3.0.0) Requirement already satisfied: hyperframe<6,>=5.2.0 in /usr/local/lib/python3.8/dist-packages (from h2<4.0,>=3.0->Twisted[http2,tls]) (5.2.0) I am using Gunicorn to … -
How to display a variable in Django forms?
I am trying to use the value of my database to display it in the form. So if a user already filled a value before, they will see it when they access again to the page. So there is my HTML file : <div class="form-group row"> <label class="col-4 mt-1 text-right">Modèle</label> <div class="col-4"> {{ form.model }} </div> </div> My views.py file : def get_car(request, identifiant): if request.method == "POST": form = CarForm(request.POST) if form.is_valid(): car_instance = Car( identifiant, form.cleaned_data["model"] ) car_instance.save() return HttpResponseRedirect("/forms/car/{}".format(identifiant)) else: form = CarForm() form.identifiant = identifiant return render(request, "forms/car.html", {"form": form}) My models.py file : class Car(models.Model): model = models.CharField(max_length=16) (primary key is automatically created) And my forms.py file : class CarForm(forms.Form): model = forms.CharField(label="Modèle", max_length=32, widget=forms.TextInput({ "value": Car.objects.get(pk=1).model})) We can see in the forms file that I gave a value to pk, so the code will search the value from the user whose pk = 1 in my database. My question is how to give the pk value from the active user ? -
Website's search function not working after a few hours (deployed using heroku)
I'm rather new at this so pardon me if I've used the wrong terminology. So the thing is that I've made a website that has Django-Machina (a forum app) integrated. Now, Django Machina comes with search functionality that uses django-haystack and whoosh. I've set up Machina according to the docs and it is working well right now. However, I realised that the search function of the Machina forum stops working after a few hours of not touching the site. To solve it, I have to run heroku run python manage.py update_index for the search to function properly again. I suspect it might have something to do with the fact that the filesystem on heroku being epipheral and each dynos boots with a clean copy of the filesystem from the most recent deploy. With that being said, how do i overcome this? I have explored the possibility of utilising cron jobs but I am honestly kinda lost. Is there any other ways around this? I would appreciate it if someone can guide me through, thank you very much!!! -
Django-filter BaseInFilter
I am currently trying to use BaseInFilter. Users can input the ids separated by commas like the one shown in the picture. I want to make a validator(or regulate user's input) so that the user can only input integers here. If the user enters characters, the Django backend will throw out this error. I have also tried this: class BaseIntegerFilter(filters.BaseInFilter, filters.NumberFilter): pass class HardwareFilter(filters.FilterSet): queryset = Hardware serializer_class = HardwareSerializer id = filters.BaseInFilter(field_name="id", label="Comma separated list of hardware IDs", help_text="Comma separated list of hardware IDs") But this solution doesn't allow me to input commas in the textbox anymore. Could anyone help? Any help will be really appreatiated! -
How to fix AttributeError: 'WhereNode' object has no attribute 'select_format', raised by Django annotate()?
There are many similar questions on SO, but this specific error message did not turn up in any of my searches: AttributeError: 'WhereNode' object has no attribute 'select_format' This was raised when trying to annotate() a Django queryset with the (boolean) result of a comparison, such as the gt lookup in the following simplified example: Score.objects.annotate(positive=Q(value__gt=0)) The model looks like this: class Score(models.Model): value = models.FloatField() ... How to fix this? -
Return UserData by taking access token input in Django Python
Code: class UserDetailsAPI(APIView): def post(self, request, *args, **kwargs): print(request.content_type) data=request.data user = data.object.get('user') or request.user token = data.object.get('access') response_data = { 'access': token, 'user': UserSer(user).data } response = Response(response_data, status=status.HTTP_200_OK) if api_settings.JWT_AUTH_COOKIE: expiration = (datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA) response.set_cookie(api_settings.JWT_AUTH_COOKIE, response.data['access'], expires=expiration, httponly=True) return response Error: AttributeError at /api/userdetails/ 'dict' object has no attribute 'object' Request Method: POST Request URL: http://127.0.0.1:8000/api/userdetails/ Django Version: 3.2.3 Exception Type: AttributeError Exception Value: 'dict' object has no attribute 'object' Plss Help -
how to call back json data in django web framework
i'm trying to display some posts as a notification class Booking(models.Model): check_in = models.DateTimeField(default=timezone.now) check_out = models.DateTimeField(blank=True,null=True) and my views.py def alerts(request): if request.is_ajax(): isnot_checked = Q(check_out__isnull=True) is_checked = Q(check_out__gte=timezone.now()) current_booking = Booking.objects.filter(isnot_checked | is_checked).order_by('-pk') return JsonResponse({'items':list(current_booking)}) my urls.py app_name = 'booking' path('notifications',alerts , name='alerts'), my template $.ajax({ url:'{% url 'booking:alerts' %}', type:'json', method:'GET', success:function(data){ let content=''; for(i = 0;i < data.items.length; i++){ content+='<div class="p-2 mt-1 text-center bgpurple textpurple">' +'<p class="p-1 text-white border-2 bgpurple rounded-3xl">'+{{i.check_in}}+'-'+{{i.check_out}}+'</p>' +'</div>' $(".allnotifi").html(content); } }}); <div class="fixed z-50 w-1/5 h-screen overflow-y-scroll shadow-xl header" id="notification"> <button class="px-4 py-1 m-2 bg-opacity-75 rounded-lg bgorange focus:outline-none " onclick="showNotifcation()"><i class="far fa-window-close"></i></button> <div class="allnotifi"> </div> </div> <button class="relative px-6 py-1 rounded-full focus:outline-none textpurple" onclick="showNotifcation()" style="background-color: #ed9720;"> <i class="fas fa-bell "></i> </button> but it returns this into the console Uncaught SyntaxError: Invalid left-hand side expression in postfix operation python = 3.6 django =3.2 , jquery : https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js is not there a better way to display some posts as notification please ? -
APScheduler:Apps aren't loaded yet when I run the script in Heroku
I created automated email and run 7 days a week, but when I call the table from my app module I got an error in heroku logs "Apps aren't loaded yet." How to fixed this error? The error happened when I call the table from app module in python script. clock.py .......some import........ from apscheduler.schedulers.blocking import BlockingScheduler import django from myapp.models import Table1 <------ error occurred from myapp.models import Table2 <------ error occurred django.setup() sched = BlockingScheduler() sched = Scheduler() @sched.cron_schedule(day_of_week='mon-sun', hour=24) def email_job(): car_status = Table1.objects.filter(Deadline__date = datetime.datetime.today()) plate = "" .......automated email code here.... procfile.py web: gunicorn core.wsgi clock: python3 core/clock.py wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") application = get_wsgi_application() Im using APScheduler==3.7.0 -
CORS with Django older version
I know there are other threads which speaks about same topic but here I have different issue. I have legacy django webserver (running with older version 1.3.1), have enabled cors as suggested in https://www.geeksforgeeks.org/how-to-enable-cors-headers-in-your-django-project/ It was working well until we stopped allowing OPTIONS method in our Apache configuration due to fix some security gaps. Now I need to ask if do we have any other way to allow OPTIONS method in Django without touching Apache configuration. After blocking OPTIONS I get below error. cors error - Cross-Origin Respurce Sharing Error: PreflightMissingAllowOrginHeader 405 method not allowed. Thanks for helping me here. -
How to pull data from a related model in a many-to-many relationship?
So, I have two applications that I want to link together in a many-to-many relationship in my project. The first application is described by the following model. model.py: class ChannelCategory(models.Model): name = models.CharField(max_length=200, db_index=True') def __str__(self): return '%s' % self.name class Channel(models.Model): category = models.ForeignKey(ChannelCategory, on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) class Meta: ordering = ['category'] def __str__(self): return '%s (%s)' % (self.category, self.name) The second application is described by the following model class Tariff(models.Model): channels_list = models.ManyToManyField(Channel, blank=True, db_index=True, symmetrical=False) def __str__(self): return '%s' % self.name def get_channels_categories(self): return ([str(p.category) for p in self.channels_list.all()]) def get_channels_objects(self): return ([str(p.name) for p in self.channels_list.all()]) Now what do I want to do? Suppose that the tariff object contains 4 channels, which have different categories, and we get approximately the following picture: tariff A has 4 channels from 2 different channel categories, for example, the "mega" tariff has ['ChannelCategory_1: Channel_1', 'ChannelCategory_1: Channel_3', 'ChannelCategory_2: Channel_2', 'ChannelCategory_2: Channel_4'] I do not understand how to display information on the interface correctly. I need to get this kind of information on my template: ['ChannelCategory_1: 'Channel_1', 'Channel_3''] ['ChannelCategory_2: 'Channel_2', 'Channel_4''] I will be glad for any help, thanks in advance!