Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I display Number in a Django Template
I have a list of Entries Generated from my Database and displayed on the template as seen below. {% for post in blog_post %} <tr> <td> S/N </td> <td><a href="{% url 'webpages:articles_detail' post.slug post.pk %}"> {{post.title}}</a></td> <td>{{post.created_on | date:"Y-m-d" }}</td> </tr> {% endfor %} How can I automatically display and increament the serial number part (labelled S_N) -
Server keep looping because of this code and I don't know why?
I want to save a second version of thumbnail field where the second version [thumbnail_low] resolution is 320 * 200 because I want my list view run faster. in creation form I accept image where the size is up to 5 megabytes and i don't want to load 5 megabytes per post. Sorry for mistakes i'm a french guy. f = BytesIO() try: copy.thumbnail((320, 200), Image.ANTIALIAS) copy.save(f, format="JPEG") b = f.getvalue() self.thumbnail_low.save("thumb", ContentFile(b)) finally: f.close() -
Error when creating an admin for the database Python (django)
1 You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). this error POPs up after 33 minutes of the tutorial: https://www.youtube.com/watch?v=zu2PBUHMEew After creating STRIPE_SECRET_KEY error when creating a superuser it was at 33 minutes approximately before that everything was fine . Help me find a solution ) -
Django/JS - Can't set default value for an already liked post
I want to check conditional on each post if the logged in user has liked it or not, accordingly I want to pass in a context which assigns the button a CSS class for the default value of color when the page loads. I don't want to use to use HTML if/else condition as I'm using JavaScript to change the color of the button when clicked. Even though I'm able to change the color once I click but I'm stuck at how to pass in the default condition of the post whenever the page loads. This is the JavaScript code : window.onload = function(){ var thumb_up = document.getElementById('thumb_up'); thumb_up.style.cursor = 'pointer'; thumb_up.onclick = function(){ var req = new XMLHttpRequest(); var id = this.getAttribute('data-id'); var url = '/api/like/'+id+'?format=json'; req.onreadystatechange = function(){ if(this.readyState==4 && this.status==200){ // var data = eval(req.responseText); data = JSON.parse(req.responseText); var likes = data.likes; document.getElementById('likes-count').innerHTML = likes+' votes'; //changing color if(data.liked=='true'){ thumb_up.className = "material-icons thumb_up_liked"; } else{ thumb_up.className = "material-icons thumb_up"; } } }; req.open("GET", url, true); req.send(); } } Also, I tried sending the default value for CSS/HTML class from backend, but I'm messing up the syntax. Can't figure out the logic to send it from backend either. … -
Configuring SSL Certificate for Django application on Apache using WAMP and mod_wsgi on Windows machine
I want to host a django web application on Apache server for which Im using WAMP server. The website is hosted and working fine but Im facing issues when Im installing SSL certificate. When I run as the intended website is shown appropriately instead it should have redirected to https://localhost and if I type https://localhost Forbidden You don't have permission to access this is shown httpd-vhosts.conf file: <VirtualHost *:80> ServerName localhost WSGIPassAuthorization On ErrorLog "C:/Django/my_project/my_project.error.log" CustomLog "C:/Django/my_project/my_project.access.log" combined WSGIScriptAlias / "C:/Django/my_project/my_project/wsgi_windows.py" <Directory "C:/Django/my_project/my_project"> <Files wsgi_windows.py> Require all granted </Files> </Directory> httpd.conf file: Here I have commented out these three lines Loadmodule ssl_module modules/mod_ssl.so, Include conf/extra/httpd-default.conf and LoadModule socache_shmcb_module modules/mod_socache_shmcb.so # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> # for a discussion of each configuration directive. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), … -
Django: Show posts with maximum upvotes
I am working on a project and I am a beginner in Django. In the project, the user can create product posts and other users can upvote it. On the homepage, I wanna show posts with maximum upvotes. I am using Postgresql as a backend. this is the view function for the homepage that returns products dictionary: def home(request): products = Product.objects return render(request, 'products/home.html', {'products': products}) as I am a beginner I am not getting any idea of how to do it in Django templates. -
Compare Rows with Latest in Django
I have a Django model stored in a Postgres DB comprised of values of counts at irregular intervals. Something like: WidgetCount - PK - Time - DeviceID - Count I can write a query to get me the latest count per device. I can write a query to get me the latest count per device which is over 24 hours old. I can write a query to get me the latest count per device which is over 7 days old. Is it possible to write something using the Django ORM to show me the difference between a number of values and the current latest value, across the whole table? So I can show either the absolute difference between 27 hours ago, and the latest, and 7 days ago and the latest? There's only a few hundred devices. I'd like to try not to use subqueries if possible. I realise I could write a few queries separately and compare the differences in Python but I wondered if this was possible using the Django ORM. Maybe something using annotate? Thanks! -
Django REST Framework: change the url to the .list() method only in a ModelViewSet
I'm making a registration api, and as I followed the docs, it recommended the use of ViewSets, so i used a ModelViewSet, now if i POST to the url '*/api/register/', I'll make a registration if provided valid fields (using .create() method), which is perfect for my case just what i needed. but when I want to list all the users for the admin, the request should be to the same url with a GET method, which is a bit weird to access '*/api/register/' to see the users... so I wanted to change the url for the .list() method to be something like '*/api/users/', but I can't find how to do that. here is what i'm doing until now: apis.py: class RegisterApi(ModelViewSet): serializer_class = UserSerializer queryset = User.objects.filter(is_active=True) def get_permissions(self): if self.action == 'create': return [permissions.AllowAny()] else: return [permissions.IsAdminUser()] def create(self, request, *args, **kwargs): response = super().create(request, *args, **kwargs) if response: response.data = dict(status=True, code=1) return response urls.py: api_router = SimpleRouter() api_router.register('register', apis.RegisterApi, basename='users') extra_urls = [path('login/', apis.LoginApi.as_view()), ] urlpatterns = [ # views urls path('', views.Home.as_view(), name='home'), path('dashboard/', views.Dashboard.as_view(), name='dashboard'), path('login/', views.LoginView.as_view(), name='login'), path('register/', views.RegistrationView.as_view(), name='register'), # api urls path('api/', include(extra_urls + api_router.urls)), ] Any hints about this? -
django updating models from views.py
How can I update the models from this updateprofile function in views.py views.py def updateProfile(request): name = request.POST['name'] email = request.POST['email'] standard = request.POST['standard'] phone = request.POST['phone'] obj, created = Student.objects.update_or_create(name=User.username, defaults={'email': email, 'standard':standard, 'phone':phone}, ) if created: messages.info(request, 'Your details are Created!', extra_tags='Congratulations!') else: messages.info(request, 'Your details are updated!', extra_tags='Congratulations!') return redirect('/profile') models.py class Student(models.Model): name = models.CharField(max_length=45, null=False, unique=True) standard = models.IntegerField(null=True) phone = models.IntegerField(null=True) address = models.CharField(max_length=100, null=True) email = models.EmailField(unique=True) password = models.CharField(max_length=20, null=True) def __str__(self): return f"{self.name} class={self.standard} rollno={self.id}" I am getting 500 error each time i try to update the Student Model.... Please help me in this problem -
Invalid hook call. Hooks can only be called inside of the body of a function
I was trying to develop a login page with the Django rest framework as the backend. The backend is working perfectly whereas I can't even set up react js. I am getting an error in the Index.js file of react. It tells "Invalid hook call. Hooks can only be called inside of the body of a function component" This is what the error I get App.js import React from 'react'; import './App.css'; import Paperbase from './Layout/Paperbase' import { BrowserRouter, Route, Switch } from 'react-router-dom'; import Login from './Layout/Login/Login' import Register from './Layout/Register/Register' export function App() { return ( <BrowserRouter> <Switch> <Route path="/dashboard" render={() => <Paperbase /> } /> <Route path="/account/login" render={() =><Login />} /> <Route path="/account/register" render={() => <Register />} /> </Switch> </BrowserRouter> ) } export default App Index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; import store from './store'; import { Provider } from 'react-redux'; import { render } from 'react-dom'; ReactDOM.render( (<Provider store={store}> <App/> </Provider>), document.getElementById('root') || document.createElement('div') // for testing purposes ); serviceWorker.unregister(); Login.js import React from 'react'; import Avatar from '@material-ui/core/Avatar'; import Button from '@material-ui/core/Button'; import CssBaseline from '@material-ui/core/CssBaseline'; import TextField from '@material-ui/core/TextField'; … -
changing "on"/"off" to True/False in views.py and saving it in database for many checkboxes
in my HTML Templates there are Checkboxes which return on/off, and django dont accept on/off it only accept true or false so how can i change on/off to true/false in views.py -
ValueError at / Required parameter name not set
I am developing a blog using Django. All is set and ready to deploy. I am using the Amazon S3 and I can't proceed because of this error ValueError at / Required parameter name not set. Please help. This is what I added to my settings.py file. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') A_KEY=os.environ.get("AWS_ACCESS_KEY_ID") A_SKEY=os.environ.get("AWS_SECRET_ACCESS_KEY") AWS_ACCESS_KEY_ID = A_KEY AWS_SECRET_ACCESS_KEY = A_SKEY AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Full Traceback: Exception while resolving variable 'url' in template 'ecommerce/home.html'. Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 828, in _resolve_lookup current = current[bit] TypeError: 'ImageFieldFile' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 836, in _resolve_lookup current = getattr(current, bit) File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\files.py", line 62, in url return self.storage.url(self.name) File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\storages\backends\s3boto3.py", line 681, in url params['Bucket'] = self.bucket.name File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\storages\backends\s3boto3.py", line 385, in bucket self._bucket = self._get_or_create_bucket(self.bucket_name) File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\storages\backends\s3boto3.py", line 422, in _get_or_create_bucket bucket = self.connection.Bucket(name) File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\boto3\resources\factory.py", line 474, in create_resource client=self.meta.client)(*args, **kwargs) File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\boto3\resources\base.py", line 119, in init 'Required parameter {0} not set'.format(identifier)) ValueError: Required parameter name not set Exception … -
How to fetch data of a particular id refrenced by foreign key django?
Following is model I have created: class Question(models.Model): title = models.CharField(max_length=255 ) description = models.TextField(max_length=300) class Quiz(models.Model): name = models.CharField(max_length=225,blank=False ) quiz_type =models.IntegerField(choices=QUIZ_TYPE,default=0) questions = models.ManyToManyField( Question, through='QuestionQuiz', related_name="quiz_question") categories= models.ManyToManyField(Category,through='CategoryQuiz',related_name='quiz_category') class QuestionQuiz(models.Model): quiz = models.ForeignKey(Quiz,on_delete=models.CASCADE) question = models.ForeignKey(Question,on_delete=models.CASCADE) correct =models.DecimalField(max_digits=4, decimal_places=3) incorrect= models.DecimalField(max_digits=4, decimal_places=3) class Meta: unique_together = ('quiz','question') Views.py - Used django_filter package to create filter class FilterQuestionView( AddQuestionAjaxFormMixin,FormMixin,FilterView): form_class = QuestionQuizForm filterset_class = QuestionFilter paginate_by = 5 context_object_name = 'questions' This is template : {% for question in questions %} <tr> <form method='POST' id="q_{{question.id}}"> <td>{{question.title}}</td> <td>{{question.description}}</td> <td><input type="text" value="1" id="correct_{{question.id}}"></td> <td><input type="text" value="1" id="incorrect_{{question.id}}"></td> <td> <a id="btn_{{question.id}}" class="btn purple-gradient" onclick="addRemoveQuestion({{question.id}},{{quiz}})" >Add</a> </td> </form> When I click add button the question along with their scores correct get +1 and incorrect -1 are updated to the database. The corresponding quiz id is send thru the url in the form : path('filter_list/<pk>',views.FilterQuestionView.as_view(),name='filter'), What I want to achieve here is when page loads initially I want to show the scored for that corresponding question based on the quiz id passed in this for {{question.questionquiz_set.all }} but this will get all the question related to id. I want to get questions related to that quiz only. -
Django model objects became not hashable after upgrading to django 2.2
I'm testing the update of an application from Django 2.1.7 to 2.2.12. I got an error when running my unit tests, which boils down to a model object not being hashable : Station.objects.all().delete() py37\lib\site-packages\django\db\models\query.py:710: in delete collector.collect(del_query) py37\lib\site-packages\django\db\models\deletion.py:192: in collect reverse_dependency=reverse_dependency) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <django.db.models.deletion.Collector object at 0x000001EC78243E80> objs = <QuerySet [<Station(nom='DUNKERQUE')>, <Station(nom='STATION1')>, <Station(nom='STATION2')>]>, source = None, nullable = False reverse_dependency = False def add(self, objs, source=None, nullable=False, reverse_dependency=False): """ Add 'objs' to the collection of objects to be deleted. If the call is the result of a cascade, 'source' should be the model that caused it, and 'nullable' should be set to True if the relation can be null. Return a list of all objects that were not already collected. """ if not objs: return [] new_objs = [] model = objs[0].__class__ … -
Django paginator sorting page is not work
i use Paginator. First page comes sorted. But when go two or other pages sorting is broken. I use this code; def mostviewdaily(request): poll = Poll.objects.filter(created_date__gte=datetime.now() - timedelta(hours=24)).order_by('-totalvotes') paginator = Paginator(poll, 30) page = request.GET.get('page') poll = paginator.get_page(page) yorumlar = Comment.objects.all() return render(request, "poll/popular.html", {"poll": poll,"yorumlar": yorumlar, }) {% if poll.has_previous %} <li class="page-item"> <a class="page-link" href="&page=1">first</a> </li> <li class="page-item"> <a class="page-link" href="&page={{ poll.previous_page_number }}">previous</a> </li> {% endif %} {% for l in poll.paginator.page_range %} {% if l <= poll.number|add:1 and l >= poll.number|add:-1 %} <li class="page-item"><a class="page-link" href="?page={{ forloop.counter }}">{{ forloop.counter }}</a></li> {% endif %} {% endfor %} {% if poll.has_next %} <li class="page-item"> <a class="page-link" href="?results={{ query }}&page={{ poll.next_page_number }}">next</a> </li> <li class="page-item"> <a class="page-link" href="?results={{ query }}&page={{ poll.paginator.num_pages }}">last</a> </li> {% endif %} How can i solve this? Thanks -
Request.Post method not working properly in django
I building quiz app. i creted 3 model Quiz , Question ,Answer Question is linked with Quiz by foreign key and Answer is linked with Question.i provided boolean field to the answer. I created radio button but its not wotking . it showing error : MultiValueDictKeyError at /quiz/2/11/ 'choice' views.py def question_detail(request,question_id,quiz_id): q = Quiz.objects.get(pk=quiz_id) que = Question.objects.get(pk=question_id) ans = que.answer_set.all() selected_choice = que.answer_set.get(pk=request.POST['choice']) if selected_choice is True: come = que.rank came = come + 1 later_question = q.question_set.get(rank=came) return render(request,'app/question_detail.html',{'que':que , 'later_question':later_question, 'ans':ans}) else: come = que.rank later_question = q.question_set.get(rank=come) return render(request, 'app/question_detail.html', {'que': que, 'later_question': later_question, 'ans': ans}) question_detail.html <form action="{% 'app:detail' quiz_id=quiz.id question_id=que.id %}" method="post"> {% csrf_token %} {% for choice in que.answer_set.all %} <input type="radio" name="choice" id="choice{{forloop.counter}}" value="{{choice.id}}"> <label for="choice{{forloop.counter}}">{{choice.answer}}</label> {% endfor %} -
How do I edit an entered data in django directly on the webpage. For eg- like in a todo app
No code for this question. I am asking this for general use in various applications -
Flask - get separates values in different sessions variables
Good day everyone, for this script I'm trying to get single values from a SQL query and store them in different session variables. I've tried to print it but I get an error : TypeError: 'ResultProxy' object is not subscriptable @app.route("/login", methods=['GET', 'POST']) def login(): if request.method == "POST": username = request.form.get("username") password = request.form.get("password") query = db.execute("SELECT * FROM accounts WHERE username = :username and password = :password", { "username": username, "password": password}) usuario = query session['id']= usuario[0] session[usuario]=usuario[1] print(session['id']) return render_template("/index.html") How can I get it to work? Let me know your responses. Thanks!!! -
Django ORM: annotate a queryset with a specific value stored in a JSONField
I would like to "annotate" a queryset (related to a model that could be called My_Model_A) with values stored in a JSONField (let's call it coefficients) of a specific instance of another model (My_Model_B). For instance, the value of coefficients could be {"6500":1, "7201":2, "2003":1.5} where 6500, 7201 and 2003 are primary keys of My_Model_A instances that I want to gather in a queryset. In that specific case, I would like to be able to easily access the values 1, 2, 1.5 in my Django QuerySet object. Concretely, what I am currently doing is this: coefficients = My_Model_B.objects.latest().coefficients # JSONField results = My_Model_A.objects.filter(pk__in=coefficients).values('pk', 'name') results = list(results) for result in results: result['coefficient']=coefficients[result['pk']] However, I guess there is a more efficient way to do that and to avoid this "for" loop, especially for big querysets. Any help appreciated. Thank you in advance! -
How to set headers in DRF's APIClient() delete() request?
When running tests, I'd like to create and then delete some resources. Access to the target server requires authenticating with a token. from django.test import TestCase from rest_framework.test import APIClient (...) class MyTest(TestCase): def setUp(self): self.client = APIClient() def test_creation_and_deletion(self): payload = {"key": "value"} # This works, but it's handled by a custom create() method from views.py: res = self.client.post(<url>, payload) (...) # This doesn't work, no custom delete() method is defined anywhere: tar_headers = {"private-token": "<token>"} res2 = self.client.delete(res.data["target_resource_url"], headers=tar_headers) Printing res2 gives the following output: <HttpResponseNotFound status_code=404, "text/html"> Deletion requests sent towards target_resource_url from e.g. Postman work fine as long as token is given in headers. How to approach this issue? -
django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known
why this error ? django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known changes i made in settings.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432 } } changes i made in dockor-compose.yml file version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 -
Why PyCharm Terminal returnung different results?
Here is similar question pycharm terminal and run giving different results as you may see there was problem with Python versions. Here what I have: (difference in the last lines output) Ubuntu Terminal: ***@***:~/Documents/Coding/Django/myfirst$ python3 manage.py shell Python 3.6.9 (default, Nov 7 2019, 10:44:02) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from articles.models import Article, Comment >>> a = Article.objects.get(id = 1) >>> a <Article: How to...?> >>> a.comment_set.all() <QuerySet [<Comment: John>, <Comment: Jack>, <Comment: Nelson>, <Comment: Bill>]> PyCharm Terminal: ***@***:~/Documents/Coding/Django/myfirst$ python3 manage.py shell Python 3.6.9 (default, Nov 7 2019, 10:44:02) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from articles.models import Article, Comment >>> a = Article.objects.get(id = 1) >>> a.id 1 >>> a.article_Title 'How to...?' >>> a.comment_set.all() <QuerySet [<Comment: Comment object (1)>, <Comment: Comment object (2)>, <Comment: Comment object (3)>]> So it`s returning id of Comment instead of Name. Many thanks for any advice! -
django charField not accepts numbers
I'm new to django and i was testing CURD and it worked correctly till i found something weird i have charfield which not accepting any numbers and showing an error when i get all records Reverse for 'updateUser' with arguments '('uuu1',)' not found. 1 pattern(s) tried views.py def signup(request): form = UserForm() if request.method == 'POST': # fullname = request.POST['fullname'] form = UserForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form = UserForm(request.POST) else: form = UserForm(request.POST) context = {'form':form} return render(request,'singup.html',context) def updateUser(request,fullname): user = User.objects.get(fullname__icontains=fullname) form = UserForm(instance=user) if request.method == 'POST': form = UserForm(request.POST, instance=user) if form.is_valid(): form.save() return redirect('/') context = {'form':form} return render(request,'singup.html',context) def getAllUsers(request): print("getAllUsers") thesearchValue = '' if 'SearchValue' in request.GET: thesearchValue = request.GET['SearchValue'] print(thesearchValue) print(request.GET['SearchValue']) allUsers = User.objects.filter(fullname__icontains=thesearchValue)#all() # return render(request,'getUsersInfo.html',{'allUsers':allUsers}) return render(request,'getUsersInfo.html',{'allUsers':allUsers}) else: print("Empty") allUsers = User.objects.all() return render(request,'getUsersInfo.html',{'allUsers':allUsers}) def deleteUser(request,fullname): print('delete the user') todelete = User.objects.filter(fullname=fullname) todelete.delete() return redirect(getAllUsers) Template <form method="GET"> {% csrf_token %} <div class="input-group"> <input type="text" class="form-control" placeholder="Search this blog" name="SearchValue"> <div class="input-group-append"> <button class="btn btn-secondary" type="button"> <i class="fa fa-search"></i> </button> </div> </div> </form> <table class="table table-bordered"> <thead> <tr> <th>Name</th> <th>Department</th> <th>Phone</th> <th>Actions</th> <th>Actions</th> </tr> </thead> <tbody> {% for x in allUsers%} <tr> <td>{{x.fullname}}</td> <td>{{x.email}}</td> <td>{{x.Resp}}</td> <td> <form … -
I installed a package outside virtual environment but cannot use it in the virtual environment
I've installed the package Pillow outside the virtual environment created using pipenv. But when I try to make migrations for my django project in this environment, it says Pillow is not installed and asks to install it. I think I installed pillow globally but it is not accessible by the pipenv virtual environment. I'm using python 3.8 and use sublime3 as editor. -
Check if object has relation with other in ManyToMany field and aggregate field
I have a couple models as follows: class Student(models.Model): name = models.CharField() classes = models.ManyToManyField(Class, related_name="students") class Class(models.Model): nombre = models.CharField What I need is a way such that, when querying students in certain class, instead of just returnig the students enrolled in that class, it returns a list of all the students, each one with an aggregated field indicating if such student is enrolled in that class, e.g.: [{'name':'student A', 'enrolled_in_physics':True}, {'name':'student B', 'enrolled_in_physics':False}] I think it can be achieved through F() expressions along with ExpressionWrapper, but have no idea of how implement them; additionaly, the documentation and the examples are not very noob-friendly. Any help is appreciated, thanks!.