Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and Chart.js - Manipulating datetime field objects to produce a graph
I have to implement some feature in Django, letting the user upload a CSV/Excel file (containing logging data of users, such as last login date, username, etc.) from Front-End. I can't share here the code as this assignment is given at work, so I mustn't publish the source code. I've already taken care of the part of uploading the file from the front-end, processing it, and populating the database (Postgres) with the users' logging details. Now, the next thing I have to do is creating a graph: Using the last_login_field that each user has in the database, I have to create a graph (linear line) showing how many users have been active per month. That is, I have to somehow retrieve only the Month/Year parts of last_login_date of all the users, and count the number of those users who share the same Month/Year in their last_login_date field. Notice that the last_login_field field is actually a standard datetime object. The problem is I don't succeed to find a way to querying the database (Postgres) to create such a table (Month/Year against Month). I'd be glad to get help overcoming this issue. -
Not Able to Add Book using Django
I have a Django Account application running in Docker container. Account is using a CustomUser. All functionality at this point is working for Accounts. Next, I have created a "Books" app to keep things separate and for easy migration. All of my activity is ran through the docker compose command for createsuperuser, makemigrations, and migrate commands. This is structure: When I look in the postgres database, I see the below: When I call up the Books application and add a book, I get the below error: Next, I go swimming in the database and identify the fault. What I discover is the created user is in the accounts_customuser table and NOT in the auth_user table. I have no records in the auth_user table. I look how the two applications are setup in the Admin portal. This is the view: The two applications handle the admin.py differently. This is accounts admin.py: This is books admin.py: I would appreciate some guidance on how to move pass this fault and align the applications to operate together. Thanks in advance. Russ -
Access control origin error for axios get method
I am trying to communicate my front end to back end, but I am keep on getting in firefox Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/getBikeParkingDetailsFromDb. (Reason: header ‘access-control-allow-origin’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response). I added below cors headers in my request also, const options = { headers : { 'Access-Control-Allow-Origin':'*'}, url: 'http://127.0.0.1:8000/getBikeParkingDetailsFromDb', method:'get' } try { let posts = await axios(options) console.log(posts) dispatch(fetchPostsSuccess(posts) ) } catch(e){ console.log(e) } and in my back end (django) I added below lines in settings.py INSTALLED_APPS = [ 'corsheaders', #rest apps ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] added response headers as well def get_bike_parking_details(request): all_bike_details = BikeParkingInfo.objects.all() serialize_data = serializers.serialize('json', all_bike_details) response = HttpResponse(serialize_data, content_type="text/json") response['Access-Control-Allow-Origin'] = '*' response['Access-Control-Allow-Headers'] = '*' return response but I am still facing same issue, currently I have used extension in chrome to make it work end to end, but need to find solution for this -
Django self.kwargs returning symbols not string. any ideas?
in this listview: context: context['first_item'] = obj_prods.filter(m_category=self.kwargs['m_category_id'], category=self.kwargs['category_id'], city=self.kwargs['city']).order_by('id').first() in production: self.kwargs['city']: returning this: %d0%91%d0%b8%d1%88%d0%ba%d0%b5%d0%ba in template and in view, so filter is not working. self.kwargs['m_category_id'] - is working as it as an integar. but in localhost is working and returning string. Only in productions is not working as it as a string. Any ideas what is going on? -
Default value is not stored in model
**This is my models class and i have given a default value to the image field** class Movie(models.Model): image = models.ImageField(default='default.jpg') title = models.CharField(max_length=255) release_year = models.IntegerField() number_in_stock = models.IntegerField() daily_rate = models.FloatField() genre = models.CharField(max_length=255) date_created = models.DateTimeField(default=timezone.now) def __str__(self): return self.title Admin interface After saving the data my image field is still empty. Whats the prooblem ? -
How to insert selected items to db in django?
Here is my Template : {% for pr in productlist %} <ul> <li><input type="checkbox" name="mylistch" value="{{ pr.productid }}"></li> <li><input type="hidden" name="mylist" value="{{ pr.productname }}"></li> <li><input type="number" name="mylist" id="prqty"/></li> </ul> {% endfor %} and View : pch = request.POST.getlist('mylistch') pnch = iter(pch) pr = request.POST.getlist('mylist') pri = iter(pr) for pid, pname, ptotal in zip(pnch , pri , pri): models.Sellinvoiceitems.objects.create( productid=pid productname=pname, totalnumber=ptotal, sellinvoice = invoice, stockid = stock ) Here i checked 5 checkbox with this ids : 6 , 9 , 10 , 12 , 19, But ids : 1 , 2 , 3 ,4 ,5 inserted to db, what is problem here? -
Is there a Django/Pythonic way of keying Django querysets by a particular value of the queryset?
I have this view that I am using in Django REST API: class HSKView(APIView): permission_classes = (AllowAny,) def get(self, request): hsk_levels = HSKLevels.objects.all() serializer = HSKSerializer(hsk_levels, many=True) return Response({"hsk": serializer.data}) And here's the serializer in case it is needed: class HSKSerializer(serializers.ModelSerializer): class Meta: model = HSKLevels fields = ["level", "label", "value"] It gives me the following output: { "hsk": [ { "level": 1, "label": "HSK 1", "value": "hsk1" }, { "level": 2, "label": "HSK 2", "value": "hsk2" }, { "level": 3, "label": "HSK 3", "value": "hsk3" }, { "level": 4, "label": "HSK 4", "value": "hsk4" }, { "level": 5, "label": "HSK 5", "value": "hsk5" }, { "level": 6, "label": "HSK 6", "value": "hsk6" }, { "level": 7, "label": "HSK 6+", "value": "hsk6plus" } ] } But ideally, I'd like to have a key to each of these items, rather than just something to iterate over, so I'd most likely to prefer it to look like this: { "hsk": { 1: { "level": 1, "label": "HSK 1", "value": "hsk1" }, 2: { "level": 2, "label": "HSK 2", "value": "hsk2" }, 3: { "level": 3, "label": "HSK 3", "value": "hsk3" }, 4: { "level": 4, "label": "HSK 4", "value": "hsk4" }, 5: … -
avoiding 502 on digitalocean and django
I am working on a ViciDial project where I need to add DIDs in ViciDial through API. But before adding any DID, I need to check if it is marked as spam-likely in any operator. I am using Django for this purpose, user can upload any number of DIDs through CSV and the script will check if any of them is flagged as spam before adding in ViciDial. I am using Telnyx API to check number status, below is my concerned code def check(request): telnyx.api_key = "api_key1234" logged_user = User.objects.get(username=request.user) all_dids = table_did.objects.filter(user=logged_user) for number in all_dids: telnyx.NumberLookup.retrieve("+1"+number.did) return HttpResponse('Finish2') But the list is huge and for loop takes time before returning any response. Obviously, I get 502 error from Nginx. (Django app is hosted on DigitalOcean with Gunicorn, Nginx and Postgres). What I am looking for is something which keeps returning response from django app to my gunicorn server after every iteration. like for number in all_dids: result = telnyx.NumberLookup.retrieve("+1"+number.did) return JsonResponse({'done':result}) I know this looks silly and there will be just one iteration, but I want to keep for loop running without getting 502. Also, it doesn't matter how long it takes, as long as the user is … -
Django traverse through relations
I've got some models which relations like this: class Conversion(models.Model): class Unit(models.IntegerChoices): g = 10, 'gramy', ml = 20, 'mililitry', qty = 30, 'sztuki' name = models.CharField(max_length=128) g = models.FloatField() ml = models.FloatField(null=True, blank=True) qty = models.FloatField(null=True, blank=True) default = models.IntegerField(choices=Unit.choices, default=Unit.g) class Ingredient(models.Model): class Unit(models.IntegerChoices): g = 10, 'gramy', dkg = 11, 'dekagramy', kg = 12, 'kilogramy', ml = 20, 'mililitry', l = 21, 'litry', qty = 30, 'sztuki' Conversion = models.ForeignKey(Conversion, on_delete=models.CASCADE, related_name='ingredients') amount = models.FloatField() unit = models.IntegerField(choices=Unit.choices, default=Unit.g) class Step(models.Model): body = models.JSONField() Ingredients = models.ManyToManyField(Ingredient, related_name='steps') class Recipe(models.Model): title = models.CharField(max_length=128) teaser = models.CharField(max_length=256) Steps = models.ManyToManyField(Step, blank=True, related_name='recipes') Say there's a conversion for flour where 1ml == .53g, and the steps are separated because of how they are displayed so I thought it would be best to put it all into separate models. Now if a user tells me he has some amount(Ingredients.amount) of ingredients(Conversion) I want to find all recipes that have equal or less of these. for example user chooses 3 ingresients: |conversion.pk|amount| |-------------|------| |1 |200 | |2 |300 | |3 |1000 | If a recipe has steps.conv.pk 1 and 2 with right amount but doesn't have the 3rd one, I want … -
django-background-tasks integration
I have a simple django app that provides a login page and an authenticated dashboard. I have created a data model, and the dashboard view displays this data, taken from the django database. I have also created a class that processes the data in this model. This class is stateful and needs to be instantiated once the django app and associated db are ready. The class is not involved in the app views directly, it only modifies db content, and uses a trigger function registered with django-background-tasks to trigger class state changes. Currently I instantiate the class in a separate file, along with the background task function, but where in the django file structure should I import this and where would be best to call the background task function? Thanks. -
login failed with correct password in django
I got an error in Django (3.1.7) when trying to login here is screenshots form.py views.py error -
How do I authorize a Google user in Python backend with ID token coming from iOS application?
Following the documentation here, I am trying to authenticate a user in my iOS app and pass their ID token to my backend. The backend handles the Google API interactions for the iOS app. I am missing how to actually authenticate that user in the backend. I read over the docs here regarding ID tokens but I am confused on where the service account comes into play. Current endpoint: @api_view(['POST']) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) def google_token_info(request): try: token_obj = json.loads(request.body) token = token_obj['id_token'] id_info = id_token.verify_oauth2_token(token, requests.Request(), settings.IOS_CLIENT_ID) # create session here - how? While testing I had authentication set up via my backend. I had code like this: def google_auth(request): web_flow = flow.Flow.from_client_secrets_file(creds, scopes=scopes) web_flow.redirect_uri = request.build_absolute_uri(reverse('api.auth:oauth_callback')) auth_url, state = web_flow.authorization_url(access_type='offline', include_granted_scopes='true', prompt='consent') request.session['state'] = state return redirect(auth_url) def oauth_callback(request): success_flow = flow.Flow.from_client_secrets_file(creds, scopes=scopes, state=request.session.get('state')) success_flow.redirect_uri = request.build_absolute_uri(reverse('api.auth:oauth_callback')) auth_response = request.build_absolute_uri() success_flow.fetch_token(authorization_response=auth_response) credentials = success_flow.credentials if not request.session.get('google_credentials'): request.session['google_credentials'] = _credentials_to_dict(credentials) return redirect(reverse('api.auth:success')) Which setup session credentials for the user. I'm assuming I need something similar, but I am unsure how to create a session without actual credentials. -
Django Editing JsonResponse
How I can add "points = " to this JsonResponse in Django? My code look like this: return JsonResponse(data=points, safe=False, json_dumps_params={'indent': 1}) Result : [ { "x": 0, "y": 1 }, { "x": 0.315397047887207, "y": 0.694608645422627 } ] what I want to do : points=[ { "x": 0, "y": 1 }, { "x": 0.315397047887207, "y": 0.694608645422627 } ] -
How to filter only request.user in online_users
I am Building a BlogApp and I am stuck on a Problem What i am trying to do I am trying to access only request.user online status in template. BUT it is showing all the active users. What i am doing I am using online_users_activity to know which user is online. The Problem It is showing all the users that are online. views.py def online(request,user_id): user_status = online_users.models.OnlineUserActivity.get_user_activities(timedelta(hours=87600)) users = (user for user in user_status) context = {'users':users} return render(request, 'online.html', context) I don't know what to do. Any help would be Appreciated. -
Using Salesforce Custom Fields from Heroku Connect in a Django app
I have a Heroku app which uses Heroku Connect to connect to my Salesforce org. I created a custom object in Salesforce and that data is syncing successfully to Heroku. I also have a Django app I am building to serve as the front end of my heroku app, which uses a Postgres database. The problem is that in Salesforce, custom objects and custom fields are appended with __c and there's no way to get around that, but in Django, __ cannot be used as in a Object/Table name or a field name. Below is my models.py class in Django: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class MyCustomObject__c(models.Model): # New class that matches the name of the object I created in Salesforce name = models.TextField() # Unrestricted text def __str__(self): return self.name # return name when MyCustomObject__c.objects.all() is called However, when I run python manage.py makemigrations to create that table in Django, I get the error: blog.MyCustomObject__c: (models.E024) The model name 'MyCustomObject__c' cannot contain double underscores as it collides with the query lookup syntax. Does anyone know how I could access the data for a Custom Object that's stored in … -
Handling Form to submit API call and display API result in the same page
I'm starting with Django journey and I'm quite confused about what I have to do here. I appreciate any help. So, basically, I'm using Form to get data and from that data, I will use a specific solution API to create a site using the information from this form. I would like to get the data from this form, create the site using the APIs, but I would like to get the API result data and display the content on the same form page but below the submit bottom. I was able to create the basic form, get the necessary data and create the site using API call, but I have no idea what I have to do to get the API result and display it in case of success. `` from django import forms from django.core.exceptions import ValidationError class SiteForm(forms.Form): site_name = forms.CharField(max_length=100, label="Site Name", widget=forms.TextInput(attrs={'placeholder': 'Demo API'})) country = forms.CharField(label="Country", widget=forms.TextInput(attrs={'placeholder': 'Country',})) time_zone = forms.CharField(max_length=100, label="Timezone", widget=forms.TextInput(attrs={'placeholder': 'City'})) location = forms.CharField(max_length=200, label="Location", widget=forms.TextInput( attrs={'placeholder': 'Street'})) I don't know if this is the best code, but the POST is working at least, I can create my site using the API call. My views.py from django.shortcuts import render import requests, … -
Django Errors, Login and Signup forms works with standard methods but not with Class Based Views
I wanted to ask you for your help. I wanted to rewrite my authentication with Class Based Views. I found several tutorials, they are all telling the same. urls.py: # Authorization: path('signup/', views.SignUpView.as_view(), name='signup'), path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView, name='logout'), views.py: class SignUpView(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('home') template_name = 'registration/signup.html' And this is part of my signup.html: <div class="jumbotron jumbotron-fluid vertical-center"> <div class="container"> <div class="d-flex justify-content-center"> {% if error %} <div style="text-align: center;"> <div class="alert alert-danger" role="alert">{{ error }}</div> </div> {% endif %} <div class="row w-75"> <div class="col-md-12"> <h1>Sign Up:</h1><br> <form method="post"> {% csrf_token %} <div class="form-group"> <label for="exampleInputEmail1">Username:</label> <input type="text" class="form-control" name="username" aria-describedby="emailHelp" placeholder="Enter username. It will be visible for others." required> </div> <br> <div class="form-group"> <label for="exampleInputPassword1">Password:</label> <input type="password" class="form-control" name="password1" id="exampleInputPassword1" placeholder="Password. Please make it strong and unique." required> </div> <br> <div class="form-group"> <label for="exampleInputPassword1">Confirm Password:</label> <input type="password" class="form-control" name="password2" id="exampleInputPassword1" placeholder="Repeat password from above." required> </div> <br> <button type="submit" class="btn btn-lg btn-success">Sign Up</button> </form> </div> </div> </div> </div> </div> And it is not working. I can see in console that POST 200 was sent but there is no redirect to home page. When I try to login nothing is happening. Also no errors are … -
'QuerySet' object has no attribute 'email'
I found an error of QuerySet object has no attribute 'email'.. i tried my best to solve the problem but don't able to find a solution.. from django.http import HttpResponse from loginsystem.models import newUser from django.contrib import messages from django.core.exceptions import MultipleObjectsReturned def login(request): if request.method=='POST': try: userdetails=newUser.objects.filter(email=request.POST['email'] , password=request.POST['password']) print("username=", userdetails) request.session['email']=userdetails.email return render(request, 'home.html') Thanks -
Django field with setter won't update even when I change the setter
To begin I will provide a background on my project / the problem I am having. The question is at the end as it makes more sense with the information first. Thank you for reading. I have a Django model which is based around tracking stock data. The first thing I do in this model is assign a score to instances of my Equity model, based on data from an Article model. def fundamental_list(self): l_fund = [] filtered_articles = Article.objects.filter(equity__industry = self.industry) for filtered_article in filtered_articles: if(filtered_article.equity.equity_name == self.equity_name): l_fund.append([filtered_article.get_fun_score(), filtered_article.get_date(), filtered_article.id, filtered_article.title, filtered_article.get_source(), filtered_article.is_this_month()]) else: if (filtered_article.read_through == -1): l_fund.append([float(-1)*filtered_article.get_fun_score(), filtered_article.get_date(), filtered_article.id, filtered_article.title, filtered_article.get_source(), filtered_article.is_this_month()]) if (filtered_article.read_through == 1): l_fund.append([filtered_article.get_fun_score(), filtered_article.get_date(), filtered_article.id, filtered_article.title, filtered_article.get_source(), filtered_article.is_this_month()]) return l_fund I then initially assigned a weighted_score to my Equity as follows (in order to rank them). weighted_strength_minus = models.FloatField(db_column='weighted_strength_minus', default=0) def set_weighted_strength_minus(self): sys.stdout.flush() weight = 0.40 fundamental_data = self.fundamental_list() sentiment_data = self.sentiment_list() num_entries = len(fundamental_data) if (num_entries != 0): total = 0 for i in range(num_entries): total += (weight**i)*(fundamental_data[i][0]-sentiment_data[i][0]) total = total*(1-weight)/(1-weight**num_entries) self.weighted_strength_minus = total return total else: self.weighted_strength_minus = 0 return 0 However, this weighted_strength incorporated too much data and I only wanted to use data from the past two weeks … -
Django: cannot annotate using prefetch calculated attribute
Target is to sum and annotate workingtimes for each employee on a given time range. models: class Employee(models.Model): first_name = models.CharField(max_length=64) class WorkTime(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name="work_times") work_start = models.DateTimeField() work_end = models.DateTimeField() work_delta = models.IntegerField(default=0) def save(self, *args, **kwargs): self.work_delta = (self.work_end - self.work_start).seconds super().save(*args, **kwargs) getting work times for each employee at a given date range: queryset = Employee.objects.prefetch_related( Prefetch( 'work_times', queryset=WorkTime.objects.filter(work_start__date__range=("2021-03-01", "2021-03-15"])) .order_by("work_start"), to_attr="filtered_work_times" )).all() trying to annotate sum of work_delta to each employee: queryset.annotate(work_sum=Sum("filtered_work_times__work_delta")) This causes a FieldError: Cannot resolve keyword 'filtered_work_times' into field. Choices are: first_name, id, work_times How would one proceed from here? Using Django 3.1 btw. -
unable to add rows and columns in spreadsheet in dash-plotly in django
I am trying to add rows and columns in spreadsheet in Django using Plotly-dash library but ,I am unable to add these in spreadsheet. I follow this link https://dash.plotly.com/datatable/editable (Uploading Data, uploading and removing rows and columns ). Can someone help me with code? Thanks in advance! -
Django related objects in hierarchy
I've got some models which relations like this: attribute: str name attribute_value: foreign attribute float value product: ManyToMany attribute_value page: ManyToManyField product Is there a way to search for a page that has products with attribute_value.attribute.pk == x and attribute_value.value == y? I've read about related objects but can I use them in this kind of relation, should I use some inner join or is there any other way I could use Django to filter it easily? -
How to select HTML Table rows by checkbox and adding to database?
Here is my Template : {% for pr in productlist %} <ul> <li><input type="checkbox" name="mylistch" value="{{ pr.productid }}"></li> <li><input type="hidden" name="mylist" value="{{ pr.productname }}"></li> <li><input type="number" name="mylist" id="prqty"/></li> </ul> {% endfor %} result is : 1 product1 23 2 product2 44 3 product3 23 4 product44 56 5 product5 12 6 product6 9 7 product7 76 Here i can get list of items via : pd = request.POST.getlist("mylist") and get selected items by checkbox via: pn = request.POST.getlist("mylistch") and View is : pch = request.POST.getlist('mylistch') pnch = iter(pch) pr = request.POST.getlist('mylist') pri = iter(pr) for pid, pname, ptotal in zip(pnch , pri , pri): models.Sellinvoiceitems.objects.create( productid=pid productname=pname, totalnumber=ptotal, sellinvoice = invoice, stockid = stock ) My problem is when i checked ids 4 , 5 , 6 via checkbox it returned ids 1 ,2 ,3. for each list it just returned first elements. how can i get id 4 ,5 ,6 which selected by checkboxes? -
uWSGI error when deploying Django app on Heroku
I'm trying to deploy a DRF app on Heroku but it keeps erroring out when building wheel for uWSGI. I'm on Heroku stack: Heroku-20 the latest The log on the command line appears like this: remote: Building wheel for uWSGI (setup.py): started remote: Building wheel for uWSGI (setup.py): finished with status 'error' remote: ERROR: Command errored out with exit status 1: remote: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-_2lmfods/uWSGI/setup.py'"'"'; __file__='"'"'/tmp/pip-install-_2lmfods/uWSGI/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-8jh6k5it remote: cwd: /tmp/pip-install-_2lmfods/uWSGI/ remote: Complete output (221 lines): remote: /app/.heroku/python/lib/python3.8/distutils/dist.py:274: UserWarning: Unknown distribution option: 'descriptions' remote: warnings.warn(msg) remote: running bdist_wheel The full log on command line is too long to post here. But further down the log there is this warning: remote: plugins/python/python_plugin.c: In function ‘uwsgi_python_worker’: remote: plugins/python/python_plugin.c:1961:3: warning: ‘PyOS_AfterFork’ is deprecated [-Wdeprecated-declarations] remote: 1961 | PyOS_AfterFork(); remote: | ^~~~~~~~~~~~~~ remote: In file included from /app/.heroku/python/include/python3.8/Python.h:144, remote: from plugins/python/uwsgi_python.h:2, remote: from plugins/python/python_plugin.c:1: remote: /app/.heroku/python/include/python3.8/intrcheck.h:18:37: note: declared here remote: 18 | Py_DEPRECATED(3.7) PyAPI_FUNC(void) PyOS_AfterFork(void); A little further down I get the failed message: remote: plugins/router_basicauth/router_basicauth.c:73:5: error: ‘struct crypt_data’ has no member named ‘current_salt’ remote: 73 | cd.current_salt[0] = ~cpwd[0]; remote: | ^ remote: ---------------------------------------- remote: ERROR: Failed building wheel … -
Using custom manager for many-to-many relations?
I have two classes (Book and Question) that are linked by a ManyToMany relationship. In particular, I typically call book.questions.all() to get all the questions in a book. Now, for my Question class, I have a custom manager active_objects, which basically only return questions that are active. What I'm trying to do is when I call book.questions.all(), I only want to return the active questions of the book using my custom manager. I was looking at previous SO questions which recommended using base_manager_name but this doesn't seem to work for me. Upon checking the documentation, they said base_manager_name does not work for ManyToMany relationships (https://docs.djangoproject.com/en/3.1/topics/db/managers/). Does anyone have a good way to do this? Class Question(models.Model): objects = models.Manager() # The default manager. active_objects = CustomManager() # custom manager. books = models.ManyToManyField(Book, related_name='questions') class Meta: base_manager_name = 'active_objects' class Book(models.Model): pass