Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying Django app to Heroku: Exception in worker process
I'm trying to deploy my Django website to Heroku. I've followed all the steps as well as I could. I created my Procfile, created the Heroku app, set the git remote, and pushed the local changes to the Heroku app. Seeing my app logs, I saw this error: 2021-01-22T10:44:54.000000+00:00 app[api]: Build started by user hassanaziz0012@gmail.com 2021-01-22T10:45:32.301870+00:00 heroku[web.1]: State changed from crashed to starting 2021-01-22T10:45:32.103906+00:00 app[api]: Release v21 created by user hassanaziz0012@gmail.com 2021-01-22T10:45:32.103906+00:00 app[api]: Deploy af87d85b by user hassanaziz0012@gmail.com 2021-01-22T10:45:36.986469+00:00 heroku[web.1]: Starting process with command `gunicorn lessonswithanative.wsgi` 2021-01-22T10:45:39.934947+00:00 heroku[web.1]: State changed from starting to up 2021-01-22T10:45:39.576978+00:00 app[web.1]: [2021-01-22 10:45:39 +0000] [4] [INFO] Starting gunicorn 20.0.4 2021-01-22T10:45:39.577706+00:00 app[web.1]: [2021-01-22 10:45:39 +0000] [4] [INFO] Listening at: http://0.0.0.0:48170 (4) 2021-01-22T10:45:39.577813+00:00 app[web.1]: [2021-01-22 10:45:39 +0000] [4] [INFO] Using worker: sync 2021-01-22T10:45:39.584050+00:00 app[web.1]: [2021-01-22 10:45:39 +0000] [10] [INFO] Booting worker with pid: 10 2021-01-22T10:45:39.595125+00:00 app[web.1]: [2021-01-22 10:45:39 +0000] [11] [INFO] Booting worker with pid: 11 2021-01-22T10:45:40.972008+00:00 app[web.1]: [2021-01-22 10:45:40 +0000] [10] [ERROR] Exception in worker process 2021-01-22T10:45:40.972058+00:00 app[web.1]: Traceback (most recent call last): 2021-01-22T10:45:40.972060+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2021-01-22T10:45:40.972061+00:00 app[web.1]: worker.init_process() 2021-01-22T10:45:40.972061+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 119, in init_process 2021-01-22T10:45:40.972061+00:00 app[web.1]: self.load_wsgi() 2021-01-22T10:45:40.972062+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2021-01-22T10:45:40.972062+00:00 app[web.1]: self.wsgi … -
Can't open zip file created with python and Django
I create a set of pdf files and whant to add them to zip archive. Everything seems fine, but when I download my zip file It can't be open. So I create pdf with create_pdf function ef create_pdf(child): buffer = io.BytesIO() canvas = Canvas(buffer, pagesize=A4) p = staticfiles_storage.path('TNR.ttf') pdfmetrics.registerFont(TTFont('TNR', p)) canvas.setFont('TNR', 14) t = canvas.beginText(-1 * cm, 29.7 * cm - 1 * cm) t.textLines(create_text(child), trim=0) canvas.drawText(t) canvas.save() pdf = buffer.getvalue() return pdf Then I create zip file and pack it to response def create_zip(pdfs): mem_zip = io.BytesIO() i = 0 with zipfile.ZipFile(mem_zip, mode='w', compression=zipfile.ZIP_DEFLATED)\ as zf: for f in pdfs: i += 1 zf.writestr(f'{str(i)}.pdf', f) return mem_zip.getvalue() def get_files(request, children): pdfs = [] for child in children: pdfs.append(create_pdf(child)) zip = create_zip(pdfs) response = FileResponse(zip, content_type='application/zip', filename='zayavleniya.zip') response['Content-Disposition'] = 'attachment; filename=files.zip' return response Please help to find where I am wrong. -
Django Template Syntax error: Could not pass the remainder
I am working on a Django project and I am relatively new to the Django framework. After running the application using python3 manage.py runserver I am getting an error like django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '['role']' from 'session['role']'. This is the particular html file to which the error is pointing. base.html {% block body %} <body> <nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0"> <a class="navbar-brand col-sm-3 col-md-2 mr-0" href="#"><img src="{% static 'img/logo.png' %} "id="icon" alt="User Icon" width="30" > {{ application.name }}</a> {% if session['role'] == "manager" %} # rest of code How do I get this done with? please help -
how to copy elements instead of moving Jquery Nestable List
I am developing app in django. I am trying to create nested list using jQuery Nestable. I would like to have two list. One, where I create my structure and second, where I store elements to use. But I would like to use one element more than ones. Is it possible to copy items from a list instead of moving them? A working demo by the author: here. An example of what I want to do: And one more question, is it possible to move items only from list A to list B (from B to A is disabled)? If not in this version then maybe in the other version of this plugin link? Best regards! -
Customize the style of a django.forms.BooleanField() containing a django.forms.CheckboxInput()
I included a contact-form on my webpage which looks like so: I would like to style the "CC myself" - checkbox in the following ways: The text "CC myself" is centered vertically within its box. The checkbox should be right next to the text "CC myself". The "forward"-symbol should be between text and checkbox, but directly next to the text and with more horizontal distance to the checkbox (on its right-hand side). This is how I defined the contact form in forms.py: from django import forms class ContactForm(forms.Form): # * Sender from_email = forms.EmailField( required=True, label='Your Email', widget=forms.TextInput(attrs={'placeholder': 'jsmith@example.com'})) # * Optional CC to sender cc_myself = forms.BooleanField( required=False, label='CC myself', widget=forms.CheckboxInput(attrs={'class': 'fa fa-share'})) # * Subject subject = forms.CharField(required=True, label='Subject') # * Message message = forms.CharField( widget=forms.Textarea(attrs={'placeholder': 'Dear Andreas ..'}), required=True, label='Message') In the home.html template then, the form is displayed like so: <form style="margin-left: auto;margin-right: 0;" method="post" action="{% url 'contact' %}"> {% csrf_token %} <!-- * Neat autoformatting of the django-form via "pip install django-widget-tweaks" Docs: https://simpleisbetterthancomplex.com/2015/12/04/package-of-the-week-django-widget-tweaks.html --> {% for hidden in sendemail_form.hidden_fields %} {{ hidden }} {% endfor %} {% for field in sendemail_form.visible_fields %} <div class="form-group"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {{ field|add_class:'form-control' }} {% … -
Random password generation when admin creates employees in admin site
I have inherited three users from the User model, namely the Admin, Employee, and Relative. models.py config = RawConfigParser() config.read('config.cfg') class UserManager( BaseUserManager): def _create_user(self, PAN_ID, password=None, **extra_fields): """ Creates and saves a User with the given email, date of birth and password. """ if not PAN_ID: raise ValueError('Users must have a PAN_ID') extra_fields['email'] = self.normalize_email(extra_fields["email"]) user = self.model(PAN_ID=PAN_ID, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, PAN_ID, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(PAN_ID, password, **extra_fields) def create_superuser(self, PAN_ID, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(PAN_ID, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): PAN_ID = models.CharField(max_length=100, unique=True) password = models.CharField(_('password'), max_length=128, null=False, blank=True) email = models.EmailField(max_length=100, unique=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) name = models.CharField( max_length=60, blank=True) address = models.CharField(max_length=70, null=True, blank=True) holding = models.CharField(max_length=100, null=True, blank=True) is_staff = models.BooleanField( _('staff status'), default=True, help_text=_( 'Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) objects = UserManager() USERNAME_FIELD = "PAN_ID" EMAIL_FIELD = "email" REQUIRED_FIELDS = ['email', … -
How to disable default Django Template/Skin
is there a way to disable Django View for users? I want to get all the data per API as Json, not from View. I tried to delete Template in Django Setting, it was okay... But after that, I couldn't access to Admin Panel. To be more clear, I mean these Templates: Thanks -
NOT NULL constraint failed: auth_user.password
Django inbuild authentication using time I'm faced this error ! ! NOT NULL constraint failed: auth_user.password Views.py from django.shortcuts import render from django.views.generic import TemplateView, FormView from .forms import UserRegistrationForm from django.contrib.auth.models import User class RegisterView(FormView): template_name = "registration/register.html" form_class = UserRegistrationForm success_url = '/' def form_valid(slef, form): username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = User.objects.create(username=username, email=email, password=password) user.save() return super().form_valid(form) Forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegistrationForm(UserCreationForm, forms.ModelForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')``` -
How to exclude an item in Django loop?
Hopefully just a quick question. I am having some difficulty wrapping my mind around to using Django loop function. I have a simple page which is fetch some data from db. Everything seems fine although loop function melting my mind. Simply my loop: {% if books %} {% for reader in books %} {{ reader.title }} {{ reader.booknumber|default_if_none:"" }} {% endfor %} {% else %} My result like: Elena 141 Elena M.Mary 1035 P.Paul 141 P.Paul T.Mark 741 T.Mark T.Mark My Expect result like: Elena 141 M.Mary 1035 P.Paul 141 T.Mark 741 Thats because some of booknumber cell is emtpy in my db. I just wonder how do i put them out of loop? I'm using defult_if_none func for hide "None" but didnt find a way for hiding\excluding title (if doesnt have booknumber). I really appreciate if someone could help me out. Thank you in advance. -
Writing Customized functions in django views
how can I return error from a python function and display it in Django temaplate. I have a code base that is similar to the following structure: In Views.py: def calculate(num1, num2): result = int(num1) + int(num2) return result def home(request): if request.method == POST: user_input_1 = request.POST.get('user_input_1 ') user_input_2 = request.POST.get('user_input_2 ') calculator = calculate(user_input_1 , user_input_2 ) context = { 'calculator' : calculator } return render(request, 'home.html', context) return render(request, 'home.html') So in the case were the user enters a letter instead of a digit, I want to display an error in the django template telling the user about the error. Right now when error occurs the code crashes. I know that I can write a try and except to handle the error but I don't know how to display the exact error message on the HTML template. Any Ideas on how to go about this please? -
How to set token expiration time according to user type in django-graphql-jwt?
Let's say we have two type of users, bot users and normal users: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True) is_bot_user = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] objects = CustomUserManager() We would want to set longer expiration time to bot user when it logs in. In settings.py we must define JWT_EXPIRATION_DELTA GRAPHENE = { 'SCHEMA': 'app.schema.schema', 'MIDDLEWARE': [ 'graphql_jwt.middleware.JSONWebTokenMiddleware', 'debugging.middleware.DebugMiddleware' ], } GRAPHQL_JWT = { 'JWT_VERIFY_EXPIRATION': True, 'JWT_EXPIRATION_DELTA': timedelta(minutes=10), } How this expiration delta can be varied according to the Users is_bot_user field? Or is there some other way to create different type of tokens for different Users -
why the image doesn't save on my code and just saved by admin page?
I need to know why the images don't save in the path. I checked from the path and both of static root and media root seems to work good but the image doesn't save, here is the code where you can see what's happening: notice: the image works fine and has installed by admin page but doesn't save or work by my code. models.py class Product(models.Model): ... image = models.ImageField(upload_to='img/', blank=True) def save(self, *args, **kwargs): if not self.image: self.image = 'empty.jpg' super().save(*args, **kwargs) settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/img/' MEDIA_ROOT = os.path.join(BASE_DIR, 'img') urls.py that exists in the project generally urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) views.py @login_required(login_url=reverse_lazy('accounts:login')) def createProduct(request, slug=None): user = User.objects.get(slug=slug) if user.user_admin: form = CreateProduct(None) if request.method == 'POST': form = CreateProduct(request.POST, request.FILES or None) if form.is_valid(): Product.objects.create( user=request.user, name=form.cleaned_data['name'], price=form.cleaned_data['price'], digital=form.cleaned_data['digital'], image=form.cleaned_data['image'] ) return redirect('store:store') return render(request, 'store/create_product.html', {'forms': form}) else: raise ValueError('You have no perm to make something here') -
how to display Time according to user location
in my website a user saves datetime in model and i need to display this time in my template according to other user's local time for instance if a user in Mexico creates a new tour it should be saved in model in Mexico time but for a user in America i want it to be displayed in US time this is my setting.py : LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True and this is my code in views.py : utc = pytz.utc date_field = form.cleaned_data['date'] time_field = form.cleaned_data['time'] meeting.date_time = utc.localize(datetime.combine(date_field,time_field)) meeting.save() and this is my template : <p class="">{{meeting.date}} {{meeting.date_time|localtime|date:'h:i A'}}</p> but it is not working! Thanks in advance! -
ImportError: cannot import name 'get_safe_settings' from 'django.views.debug' when upgrading django2 to 3.1.5
I am trying to upgrade from Django2.2.6 to Django 3.1.5. I have already upgraded few installed packages, but I do not know which one causes the following error: Exception in thread django-main-thread: Traceback (most recent call last): File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/channels/management/commands/runserver.py", line 69, in inner_run self.check(display_num_errors=True) File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/debug_toolbar/apps.py", line 18, in check_middleware from debug_toolbar.middleware import DebugToolbarMiddleware File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/debug_toolbar/middleware.py", line 12, in <module> from debug_toolbar.toolbar import DebugToolbar File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/debug_toolbar/toolbar.py", line 141, in <module> urlpatterns = DebugToolbar.get_urls() File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/debug_toolbar/toolbar.py", line 134, in get_urls for panel_class in cls.get_panel_classes(): File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/debug_toolbar/toolbar.py", line 115, in get_panel_classes panel_classes = [ File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/debug_toolbar/toolbar.py", line 116, in <listcomp> import_string(panel_path) for panel_path in dt_settings.get_panels() File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/debug_toolbar/panels/settings.py", line 5, in <module> from django.views.debug import get_safe_settings ImportError: cannot import name 'get_safe_settings' from 'django.views.debug' (/home/admin1/miniconda3/envs/new_python_env/lib/python3.9/site-packages/django/views/debug.py) -
Python Django SQLite Database is Locked
I am using Python Django and trying to save some data in Admin panel but it throws an error Please help to solve thisThanks -
How to manage mobile and web authentication with Django Rest and react/react native?
We are in the process of setting up a project that requires mobile and web app authentication and were wondering if there are any best practices for implementation. For the backend we are currently using django rest framework with a knox token authentication and for the web frontend react.js. For the future, there will be a mobile app in react native. We want to set up the authentication now so that it supports the react native mobile app in the future. However, I have seen that Knox authentication does not work for mobile apps straight forward as it uses csrf token. So I'm wondering if there are any best-practices for mobile app and web authentication that specifically feature good documentation, multi-device login and smooth extensibility of login options (fb, google etc) for the current setup drf and react.js/react native. I'm grateful for any guiding hints. -
Django in qpython
Hi I program in Android Python But I have a problem, thank you for your help I installed Django completely and created the Manage.py folder, now I have a problem with runserver python manage.py runserver There is an error for the word Python here! What should I do? -
PostgreSQL HStore() field
I use multiple PostgreSQL HStore fields in my django model. Keys of HStore fields are big int numbers that are related to some other fields in application and are therefore random, not predefined. Values are decimal numbers. Like so: "10intNumber" => "DecNumber". All hstore fields have the same 10IntNumber keys in them, even if DecNumber is 0. The model also include a foreign key to user, and a status. Status is 1: only the hstore_field_1 is evaluated and summed. Status is 0: both hstore_field_1 and hstore_field_2 are evaluated and summed. I use a SQL Query like this, to sum all the DecNumber in values for predefined 10intNumber, where d.number is the 10IntNumber from before and is retrieved from another queryset.: query = f""" SELECT SUM(hstore_1::numeric) AS hstore_1_field, SUM(hstore_2::numeric) as hstore_2_field, FROM ( SELECT UNNEST(hstore_field_1-> ARRAY {[str(d.number) for d in queryset]}) AS hstore_1, UNNEST(CASE WHEN status = '0' THEN hstore_field_2-> ARRAY {[str(d.number) for d in queryset]} ELSE ARRAY ['0'] END) AS hstore_2, FROM public.app_model WHERE hstore_field_1?| ARRAY {[str(d.number) for d in queryset]} ) AS b; """ I also use a SQL query to group sums by related user_id and user__othemodel_id. But my knowledge of SQL comes short afterwards. I would like … -
tag inside bootstrap_button tag in django-bootstrap4
I have a question regarding the bootstrap_button template tag of django-bootstrap4 (https://django-bootstrap4.readthedocs.io/en/latest/templatetags.html#bootstrap-button) , could it be possible to include a tag from my tags in the href, something like this : {% bootstrap_button "Supprimer" button_type="link" href="../../delete/{{article.id}} " button_class="btn-danger" %} but {{article.id}} is not interpreted and it gives me a link to http://127.0.0.1:8000/delete/{{article.id}} I also tried : {% bootstrap_button "Supprimer" button_type="link" href="{% url 'delete' article.id %}" button_class="btn-danger" %} it returns TemplateSyntaxError at /edit/127/ Could not parse the remainder: '"{%' from '"{%' Request Method: GET Request URL: http://127.0.0.1:8000/edit/127/ Django Version: 3.0.5 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '"{%' from '"{%' but none of thos syntax is not working... Could you help me to make it work ? Man thanks -
Error while accessing CSS file Type scan linked CSS file
My code is not bad i think i have checked different websites and i have done what they did but for some reason my html code doesnt accept the css code in django {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> I have tried everything and honestly it is fustrating -
DJANGO PWA Install to home screen not working
I am trying to follow the instructions on this site (https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Add_to_home_screen) with my DJANGO app to make a PWA "Install to home screen' button. I have SSL installed on the site, and it seems to me that the service worker is installed properly, I got the "Service Worker Registered" message back. However when I click the button I nothing happens, the + sign does not appear in the URL bar as it should. I have no idea what is causing the error, as there is no clear sign of anything not working properly. My index.html: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>A2HS demo</title> <link href="{% static 'css/index.css' %}" rel="stylesheet"> <script src="{% static 'js/index.js' %}" defer></script> <link rel="manifest" href="{% static 'manifest.json' %}"> </head> <body> <button class="add-button">Add to home screen</button> </body> </html> My manifest.json: { "short_name": "Test site", "name": "Test site", "theme_color": "#062440", "background_color": "#F7F8F9", "display": "fullscreen", "icons": [ { "src": "assets/logo.png", "type": "image/png", "sizes": "192x192" } ], "start_url": "/index.html" } My index.js // Register service worker to control making site work offline if ('serviceWorker' in navigator) { navigator.serviceWorker .register('/static/js/service-worker.js') .then(() => { console.log('Service Worker Registered'); }); } // Code to handle install prompt on desktop let deferredPrompt; … -
In Django what does the request argument in a method do?
I have seen a few codes where sometimes the authenticate method have the request argument while other times it does not, e.g. see the below codes: Code 1: def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() # code for automatic login after singing up username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) return redirect('/') Code 2: def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) According to the official docs: request is an HttpRequest and maybe None if it wasn’t provided to authenticate() (which passes it on to the backend). What does this request argument actually do and when should I consider passing it in the authenticate or login method? Is there any specific reason for which request argument is present or absent in the above codes? -
how to solve static file error in my django app
Request Method: GET Request URL: http://127.0.0.1:8000/static/mytxt.txt 'mytxt.txt' could not be found -
Unable to follow django-quickbooks Documentation
I am working on Django web application and i want to push data in Quickbook Desktop. So i was following https://github.com/weltlink/django-quickbooks/ this link and in the third step where you have to create qwc file with manage.py command is not working. So, Is there any better way to integrate django and quickbook desktop? Or Is there any better Documentation? -
How do you access a ForeignKey's other attribute in Django?
I've been looking for a way to retrieve a model's attribute via ForeignKey(related_name). I'm going to paste the code below. Django version is 3.1, while Python version is 3.7. accounts.models.py class Company(models.Model): name = models.CharField(max_length=60) industry = models.CharField(max_length=20, choices = INDUSTRY_CHOICES, default="agriculture") partner.models.py class Partnership(models.Model): created = models.DateTimeField(auto_now_add=True, editable=False) creator = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="partnership_creator_set") partner = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="partner_set") So when a Company partners with another Company, 2 instances of Partnerships are created. How do i get get the number of existing partners for a specific company? I'm able to get a Company instance then use the related name to get the existing partnerships. If I try something like Company.partnership_creator_set.all(), I'm able to get the list of partnerships. What I want is to look for the current partners which is in the "partner" attribute in the Partnership model.