Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how send notification to user when admin model save function in django admin site
i am preparing an e commerce site where i want to send notification on orders like ( processing , dispatched, on the way etc. ) these items are filled by the admin in their site. now my query is to send notification to the user when the admin fills the field and saves it. class orders(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) pid=models.ForeignKey(products,on_delete=models.CASCADE) amount=models.FloatField() isaddfilled=models.BooleanField(default=False) ispaymentdone=models.BooleanField(default=False) delivered=models.BooleanField(default=False) status=models.CharField(max_length=255,blank=True) when the admin fills the status and saves it. the status should be sent as the push notification to the user. -
How to search a Django database using a field saved in the model?
I am trying to create a search bar that searches for users in my Journal app. I want to redirect the search to the appropriate page if the user exists. I have created the view function, template and URL for the feature. As a test, I imported the User class from django.contrib.auth.models and I was able to display a personalised message if the user existed. def search_user(request): """Search for users.""" if request.method == "POST": searched = request.POST["searched"] usernames = User.objects.filter(username__icontains=searched) context = {"searched": searched, "usernames": usernames} return render(request, "journals/search_user.html", context) In the main model, the Journal class has a ForeignKey relation with User and it is saved to a field called "owner". I would like to somehow check if the searched username matches with this "owner" field. When I try to make a search this way, it cannot find any data. The reason I want the search to refer to "owner" is so that I can access the other fields in the table. Could someone point out the mistake I am doing here? from django.db import models from django.contrib.auth.models import User class Journal(models.Model): """A particular subject the user may want to write about.""" name = models.CharField(max_length=100) date_added = models.DateTimeField(auto_now_add=True) owner … -
How to write a variable of a model by index
Assuming a model class MyModel(models.Model): id_pk = models.AutoField(primary_key=True) prop_a = models.CharField(max_length=200, blank=True, null=True) prop_b = models.CharField(max_length=200, blank=True, null=True) prop_c = models.CharField(max_length=200, blank=True, null=True) I want to access the variables (=columns) per index (integer) like: my_model = MyModel() my_model[2] = 'my text' I know one can do this "statically" by using the variable name: g = MyModel.objects.get(id_pk=id) g.prop_b = 'my text' g.save() But I want to do it "dynamically". Using _meta seems also not be possible: MyModel._meta.fields[2] = 'my text' reports AttributeError: The return type of 'fields' should never be mutated. and g = MyModel.objects.filter(id_pk=id) list(g.values()[0])[2] = 'my text' just changes at in a copy. -
Where to load Tensorflow model in Django application
I am working on a Django project that should load a saved Tensorflow model from a file. Where should I run this code to have a global model variable? Currently, I am just loading in the model in the views.py file outside of all functions and it is working, but I am unsure if this runs only once and if it is a clean solution. -
Python, Django Celery job interface upgrade to ubuntu 20.04 celery jobs not running
Very New to Celery/Django Over the weekend, we upgraded the ubuntu server to 20.04, and while the web interface is up and running and I can see the defined jobs when I attempt to run any job the job does not run. I am not seeing any errors in the logs (assuming I am looking at the correct apache logs). Everything is down and I am not sure where to debug celery. If I could find out where the jobs are located then I would try to run using the celery CLI. Any help/pointers is much apprecited. -
Django html button is not opening web browser with selenium
I want a button on my django project home page that when clicked runs a .py file and opens a new browser using selenium. Following is my code but it is not working - html - <form method="post"> {% csrf_token %} <button type="submit" name="run_script">Generate Challan</button> </form> views - # import function to run from .generate import Generate def Generate(request): if request.method == 'POST' and 'run_script' in request.POST: # call function GenerateChallan() Python script in generate.py - from selenium import webdriver import time from selenium.webdriver.common.action_chains import ActionChains class Generate(): def GenerateChallan(): driver = webdriver.Chrome() driver.get('https://onlineservices.tin.egov-nsdl.com/etaxnew/tdsnontds.jsp') driver.set_window_size(1920, 1012) driver.implicitly_wait(5) driver.execute_script('javascript:sendRequest(281)') There is no error but the browser is not opening. Please help -
Django looking for variable i can use in object.filter
I am using a for loop to get data from a database and a html page shows every db entry as a different card, with a button under it. If i click the button, it should show me a html page with more information. On that page i use <a href="receptinfo?{{recepten.name}}" class="btn btn-info knop">Meer Info</a> and this works. The url shows : localhost/receptinfo?Babi%20pangang In views.py try to setup a filter for objects.filter( ) which uses a variable. I tried: recepten = Recept_Info.objects.filter(name='{{recepten,name}}'), it doesn't show any errors, but also it shows no data. When i try: recepten = Recept_Info.objects.filter(name={{recepten,name}}), i get UnboundLocalError: local variable referenced before assignment error. If i write: recepten = Recept_Info.objects.filter(name='Babi pangang') it works. My question is how can i use the name i get from {{recepten.name}} as object.filter(......) recept.html <div class="container"> {% for recepten in recepten %} <div class='row'> <div class="data-aos="zoom-in" data-aos-delay="200"> <div class="card-deck"> <div class="card"> <div class="card-body"> <h4 class="card-title">{{recepten.name}}</h4> <ul> <li><p class="card-text">Menugang: {{recepten.menugang}}</p></li> <li><p class="card-text">Keuken: {{recepten.keuken}}</p></li> <li><p class="card-text">Bereidingstijd: {{recepten.bereidingstijd}} min.</p></li> <li><p class="card-text">Personen: {{recepten.aantal_personen}}</p></li> <li><p class="card-text">Vegetarisch : {{recepten.Vegetarisch |yesno:"Ja,Nee" }}</p></li> <ul> </div> <a href="receptinfo?{{recepten.name}}" class="btn btn-info knop">Meer Info</a> </div> </div> {% endfor %} </div> </div> <div class="end"> </div> Views.py def receptinfo(request): recepten = Recept_Info.objects.filter(name='{{recepten,name}}') return render(request, … -
What JSESSIONID cookie when connecting to Spotfire server?
I am embedding a Spotfire visualization into my Django webpage. I am using the following JS API: https://community.tibco.com/wiki/spotfire-tipstricks-embed-spotfire-visualizations-webpages The API works well except that it gives me a cookie error like the following: How can I solve this? -
Cors Headers error Django 1.11 accessing data from different port
I have upgraded my python version from 3.4 to 3.8 after doing that upgradation I am getting cors headers error Access to XMLHttpRequest at '10.31.101.66:8081/administration/UserLogin/' from origin '10.31.101.66:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource this error occurs when one port try's to access data from the second port. -
How do I insert a parser into a django structure?
I am writing a website on the Django framework. Created a standard Django structure, changed SQLite to PostgreSQL. I wrote a parser in a separate .py file. Then I sketched out the structure for the database. The problem is that I don't know where to insert the code with the parser. I will need, for example, that the parser is loaded once a day, updating my database. There is an idea to insert a parser into the models.py but, but I do not know how to work correctly. -
Launching celery worker creates too many connexions to redis
I'm using celery with redis as a broker in a django project. The problem I have is that even with no task running, just launching the worker produces up to 10 new connexions to redis server. celery -A proj worker -l INFO If I check CLIENT LIST in redis-cli I see this: 127.0.0.1:6379> CLIENT LIST id=272 addr=127.0.0.1:48846 fd=16 name= age=63 idle=63 flags=N db=2 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 argv-mem=0 obl=0 oll=0 omem=0 tot-mem=20520 events=r cmd=sadd user=default id=270 addr=127.0.0.1:48842 fd=14 name= age=64 idle=64 flags=N db=2 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 argv-mem=0 obl=0 oll=0 omem=0 tot-mem=20520 events=r cmd=publish user=default id=4 addr=127.0.0.1:46946 fd=8 name= age=14901 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=32742 argv-mem=10 obl=0 oll=0 omem=0 tot-mem=61466 events=r cmd=client user=default id=265 addr=127.0.0.1:48832 fd=9 name= age=64 idle=0 flags=b db=2 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 argv-mem=0 obl=0 oll=0 omem=0 tot-mem=20536 events=r cmd=brpop user=default id=266 addr=127.0.0.1:48834 fd=10 name= age=64 idle=63 flags=N db=2 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 argv-mem=0 obl=0 oll=0 omem=0 tot-mem=20520 events=r cmd=sadd user=default id=273 addr=127.0.0.1:48848 fd=17 name= age=63 idle=2 flags=P db=2 sub=0 psub=1 multi=-1 qbuf=0 qbuf-free=0 argv-mem=0 obl=0 oll=0 omem=0 tot-mem=20504 events=r cmd=psubscribe user=default id=274 addr=127.0.0.1:48850 fd=18 name= age=63 idle=63 flags=N db=2 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 argv-mem=0 obl=0 oll=0 omem=0 tot-mem=20520 events=r … -
table only shows the first page in Django pagination
I have developed a web app using Django. I have created a table pagination. But only the first view of the table shows(no pagination created). Where is my error? view.py def Browse_and_adopt(request): Title_list = Title.objects.all() page = request.GET.get('page', 1) paginator = Paginator(Title_list, 10) try: Titles = paginator.page(page) except PageNotAnInteger: Titles = paginator.page(1) except EmptyPage: Titles = paginator.page(paginator.num_pages) return render(request, 'bms/inbox/Browse_and_adopt.html', {'Titles': Titles}) Browse_and_adopt.html <table id="myTable"> <thead> <tr> <th>Title</th> </tr> </thead> <tbody> {% for book in Titles %} <tr> <td>{{ book.title }}</td> </tr> {% endfor %} </tbody> </table> <script> $(document).ready(function() { $(".dataTables_filter input").attr("placeholder", "By title, "); var table = $('#myTable').DataTable(); $('#myTable tbody').on('click', 'tr', function () { if ($(this).hasClass('selected')) { $(this).removeClass('selected'); } else { table.$('tr.selected').removeClass('selected'); $(this).addClass('selected'); } }); }); </script> -
Why is it returning 204 instead of 403? Custom permissions does not working
I have a table that stores parent - child records. Today, I noticed a problem while writing a unit test. Even if the requester is not the parent of the child, they can delete the record. But on the view side, if the user is not the owner of the record, the delete button is not active. So it works in the view side. If I make the request using postman, the record is deleted regardless of who owns it. How can I check that whether the user is the owner of the record? I am following an example project and the creator of that project has done a similar permission. Child List Model class ChildList(models.Model): parent = models.ForeignKey( "account.ParentProfile", on_delete=models.CASCADE, related_name="parent_children", verbose_name=AccountStrings.ChildListString.parent_verbose_name) child = models.OneToOneField( "account.ChildProfile", on_delete=models.CASCADE, related_name="child_list", verbose_name=AccountStrings.ChildListString.child_verbose_name) def __str__(self): return f"{self.parent.user.first_name} {self.parent.user.last_name} - {self.child.user.first_name} {self.child.user.last_name}" class Meta: verbose_name = AccountStrings.ChildListString.meta_verbose_name verbose_name_plural = AccountStrings.ChildListString.meta_verbose_name_plural Child List Destroy View class ChildListItemDestroyAPIView(RetrieveDestroyAPIView): """ Returns a destroy view by child id value. """ queryset = ChildList.objects.all() serializer_class = ChildListSerializer permission_classes = [IsAuthenticated, IsParent, IsOwnChild] def get_object(self): queryset = self.get_queryset() obj = get_object_or_404(ChildList,child = self.kwargs["child_id"]) return obj Permission class IsOwnChild(BasePermission): """ To edit or destroy a child list record, the user must … -
How to solve python model to called by a web using django
i'm a beginner for python django, and i try to input my model (the model that i've train at google collab using CNN) for classification of Braille, but when i test the model, there is error like [no such file or directory ][1] can you solve this? am i wrong with the code? [1]: https://i.stack.imgur.com/Bo077.jpg this is the code : def prosesImg(request): filelink = request.POST.dict().get("myfiles") tf.compat.v1.disable_eager_execution() img_height, img_width=224,224 model_graph = tf.Graph() with model_graph.as_default(): tf_session=tf.compat.v1.Session() with tf_session.as_default(): models=load_model('./model/BrailleNet.h5') testimage='.'+filelink img = image.load_img(testimage, target_size=(img_height, img_width)) x = image.img_to_array(img) x = x / 255 x = x.reshape(1, img_height, img_width, 3) with model_graph.as_default(): with tf_session.as_default(): predi = models.predict(x) if np.argmax(predi) == 0: predictedLabel = """Classification : huruf A <br/>""" elif np.argmax(predi) == 1: predictedLabel = """Classification : huruf B <br/>""" elif np.argmax(predi) == 1: predictedLabel = """Classification : huruf C <br/>""" elif np.argmax(predi) == 1: predictedLabel = """Classification : huruf D <br/>""" elif np.argmax(predi) == 1: predictedLabel = """Classification : huruf E <br/>""" elif np.argmax(predi) == 1: predictedLabel = """Classification : huruf F <br/>""" elif np.argmax(predi) == 1: predictedLabel = """Classification : huruf G <br/>""" elif np.argmax(predi) == 1: predictedLabel = """Classification : huruf H <br/>""" elif np.argmax(predi) == 1: predictedLabel = """Classification : … -
How to create unlimited number of headings for the template
''' class blogpost(models.Model): created_by=models.ForeignKey(User,on_delete=models.CASCADE) topic=models.CharField(max_length=122,null=False) title=models.TextField(blank=False) slug=models.SlugField(max_length=250,null=True) post=models.TextField() #more other headings and their text which can only be added from admin pannel heading1=models.CharField(max_length=250,blank=True) post1=models.TextField(blank=True) heading2=models.CharField(max_length=250,blank=True) post2=models.TextField(blank=True) heading3=models.CharField(max_length=250,blank=True) post3=models.TextField(blank=True) likes=models.ManyToManyField(User, related_name='blog_posts',blank=True) date=models.DateTimeField(auto_now_add=True ) ''' Above i have created different fields for every heading to print on the template but if i want to store unlimited or unknwon number of headings and their associated text then what can i do??? <div> <p class='fs-5 fw-light'>{{data.post | linebreaks}}</p> </div> <div> <h4>{{data.heading1}}</h4> <p class='fs-5 fw-light' > {{data.post1 | linebreaks}}</p> </div> <div> <h4>{{data.heading2}}</h4> <p class='fs-5 fw-light' > {{data.post2 | linebreaks}}</p> </div> <div> <h4>{{data.heading3}}</h4> <p class='fs-5 fw-light'> {{data.post3 | linebreaks}}</p> </div> -
Saleor-Storefront has error:Redis adress already in use
Hi everyone i have a problem with redis when i call migration: sudo docker-compose run --rm api python3 manage.py migrate I tried to stop, disable, shutdown redis, close ports etc. but nothing seemed to work. Can anyone help me? I am desperate My error screen: Starting saleor-platform_jaeger_1 ... done Starting saleor-platform_db_1 ... done Starting saleor-platform_redis_1 ... Starting saleor-platform_redis_1 ... error ERROR: for saleor-platform_redis_1 Cannot start service redis: driver failed programming external connectivity on endpoint saleor-platform _redis_1 (af785cb919fe2290aeedfc681fe4a39767b94b59856b1ed779f5 9587ef354401): Error starting userland proxy: listen tcp 0.0.0.0:6379: bind : address already in use ERROR: for redis Cannot start service redis: driver failed programming external connectivity on endpoint saleor-platform_redis_1 (af785cb919 fe2290aeedfc681fe4a39767b94b59856b1ed779f59587ef354401): Error starting userland proxy: listen tcp 0.0.0.0:6379: bind: address already in use ERROR: Encountered errors while bringing up the project. I tried all of these commands and migrated again: sudo service redis stop sudo update-rc.d redis_6379 defaults sudo /etc/init.d/redis-server stop redis-cli shutdown redis-cli shutdown nosave sudo killall redis-server sudo killall redis-cli sudo kill -9 `sudo lsof -t -i:6379` sudo kill -9 $(sudo lsof -t -i:6379) None of them worked though. I think my 6379 port is still open but i cannot close it -
Python manage.py Identified 0 errors but unable to runserver
I have not been able to run my server even with 0 errors, it shows me this: Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000028159B61048> Traceback (most recent call last): File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\core\management\commands\runserver.py", line 123, in inner_run self.check_migrations() File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\core\management\base.py", line 427, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\loader.py", line 268, in build_graph raise exc File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\loader.py", line 242, in build_graph self.graph.validate_consistency() File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\graph.py", line 243, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\graph.py", line 243, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\graph.py", line 96, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration admin.0004_auto_20190704_0341 dependencies reference nonexistent parent node ('admin', '0003_logentry_add_action_flag_choices') -
If/when statement in django models to create another model field
I'm trying to create a model field that is a result of another model field. I am unable to articulate this properly, but I will try anyway. I have employees who include everyone in the office, then I have a role for them too. All the staff are Engineers, and a few of the Engineers are also Managers. so when creating an Employee, I have to select if they are just an Engineer or a Manager. if the role is a Manager, then I want to create a model field as manager = models.Charfield(???????????) from django.db import models class Roles(models.Model): role = models.CharField(max_length=22) def __str__(self): return self.role class Engineers(models.Model): region = ( ('SS', 'South-South'), ('SW', 'South-West'), ('SE', 'South-East'), ('NE', 'North-East'), ('NW', 'North-West'), ('NC', 'North-Central'), ) firstname = models.CharField(max_length=20) lastname = models.CharField(max_length=20) email = models.EmailField(max_length=50) username = models.CharField(max_length=20, unique=True) phone = models.CharField(max_length=11) position = models.ForeignKey(Roles, on_delete=models.DO_NOTHING, max_length=20) workarea = models.CharField(max_length=20, choices=region) manager = models.(if role selected = Manager), then the Employee name should be here def __str__(self): return self.firstname + ' ' + self.lastname I'd appreciate any help or redirection to any resources that can help, or any different way of doing this. -
How to get Image uploads in HTML to be of ratio 1:1
I am using the Django framework to allow drivers to register with my site, and one of the fields that they need to submit is a picture of themselves. A snippet of code from forms.py... your_picture = forms.ImageField(help_text="A picture of yourself so that we know who you are") I want to make sure always that the user inputs an image that is 1:1. Especially when it comes to mobile devices and the user selects an already available picture, I need it to allow the user to crop it as a 1:1, like how I have seen in many different applications. I want to know how I can do a client-side check and a server-side validation to see if the image meets my requirements. Just for your information, the images are stored and uploaded into AWS S3. Any support would be greatly appreciated thanks! -
django - Restrict "n" or More Characters Present in a Previous Password
I am using django for password management and I understand that DJango uses one-way hash to store passwords. My application is using django.contrib.auth.hashers.PBKDF2PasswordHasher I have a table PasswordHistory where I save last 10 passwords. Passwords are saved using django hashing. I want to restrict user to have a password with "n" or more characters present in a previous password. Right now, it is not possible as I can not get password from hashed string. Is there a way to do so using django? Otherwise, I will have to save passwords using my own encryption/decryption logic. I know this is not a secure way, but may be the last option I have. -
Django, store Post object with image in post field of other object
I have a problem in django and I don´t know how to solve it. I have a class named "Post", including an image, a recipe and a caption. After that, I just want to store the Post-object in the field "posts" of my Client-class. But it is not working, I get the error Object of type AddForm is not JSON serializable. Probably the error is in my models.py, but I can´t figure out where. I appreciate any help, and thanks in advance. forms.py class AddForm(forms.ModelForm): image = forms.FileField() caption = forms.TextInput() recipe = forms.TextInput() class Meta: model = Post fields = ["image", "recipe", "caption"] models.py def default_posts(): return {"posts": []} class Client(models.Model): posts = models.JSONField(default=default_posts) class Post(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True, blank=True) image = models.ImageField(upload_to="images/") caption = models.TextField(default=None) recipe = models.TextField(default=None) views.py @login_required(login_url="login") def add(response): if response.method == "POST": form = AddForm(response.POST, response.FILES) if form.is_valid(): form.save() current_user = Client.objects.get(id=response.user.id) current_user.posts["posts"].append(form) current_user.save() return redirect("home") else: form = AddForm() return render(response, "main/add.html", {"form":form}) -
Retrieve set of data only with one query | Django
I have a following question. For example I have a Django model with 2 field ( it is not a real model but carries in itself same conception, all other fields are omitted for a sake of simplicity): class Foo(models.Model): id = models.UUIDField() created = models.DateTimeField(auto_now_add=True) Lets say we have 1000 entries of this model in database and we have an UUID in input data that might or might not belong to one of these 1000 entries ( id field) Goal is like this: Get following data with maximum of 1 query to database without retrieving whole set of data from database as well Whether or not one of these 1000 entries has this UUID as id field? If so, we need created field of this exact entry Whether or not there are at least 100 entries in database that have created field earlier then this exact entry ( where id == UUID) Django 3.2 Thanks -
how do i import / export social accounts using django import export package?
I successfully imported and exported other data but not able to import/export social accounts and social application tokens. I am using django allauth for social account creation. There is no other way to login in. -
Optomizing Django API Queries to reduce database hits
This is just on my belief that Django has unlimited possibilities. I have an API, testing it with debug-toolbar, I have up to 13 hits per request. I would like to think there is something I can do to bring down the database hits to 1. Here is my API List View: class ProductsListAPIView(ListAPIView): queryset = Product.objects.active() serializer_class = ProductSerializer filter_backends = [SearchFilter, OrderingFilter] permission_classes = [HasAPIKey | AllowAny] search_fields = ['product_title', 'product_description', 'user__first_name', 'product_type', 'product_price', 'product_city'] pagination_class = ProductPageNumberPagination def get_serializer_context(self, *args, **kwargs): context = super(ProductsListAPIView, self).get_serializer_context(*args, **kwargs) context['request'] = self.request coordinates = self.request.GET.get("coordinates") if not coordinates or len(coordinates) <= 4: coordinates = '0.0,0.0' context['coordinates'] = coordinates return context def get_queryset(self, *args, **kwargs): query = self.request.GET.get("search") lookups = () if query and len(query) > 0: queryArray = query.split() for q in queryArray: lookups = (Q(product_title__icontains=q) | Q(product_description__icontains=q) | Q(product_type__icontains=q) | Q(product_city__icontains=q) | Q(user__first_name__icontains=q) | Q(user__last_name__icontains=q) | Q(product_address__icontains=query) ) # If user is loggedIn and discovery range / point and address is set # Returns products just in that range. uid = self.request.GET.get("uid") queryset_list = self.queryset if uid and len(uid) > 5: try: user = CustomUser.objects.get(uid=uid) from django.contrib.gis.measure import D if user is not None and user.point is not None … -
How can you group a list extracted from queryset many-to-many field?
I have a model that describes the essence of a TV channel: 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) I also have a model that describes the essence of the tariff. Channels are linked to a tariff using a relationship many-to-many. class Tariff(models.Model): channels_list = models.ManyToManyField(Channel, blank=True, db_index=True, symmetrical=False) def __str__(self): return '%s' % self.name If I call the tariff object, I can get a list of channels that are assigned to it: queryset = Tariff.objects.prefetch_related('channels_list') for tariff in queryset: channels_list = [tariff.channels_list.all()] print (channels_list) And get the next set: <QuerySet [<Channel: channelcategory1: channel1>, <Channel: channelcategory1: channel2>, <Channel: channelcategory2: channel3>]> I want to receive queryset the following form: <QuerySet [<Channel: channelcategory1: channel1, channel2>, <Channel: channelcategory2: channel3>]> How can I do that?