Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FastAPI vs Django- can't explain "hello world" benchmark results
I was wanted to benchmark FastAPI(0.68.1) and Django(3.2.6) and compare the results of a simple "Hello World" applications. (Python 3.8.5) The code for FastAPI (ran it with uvicorn): from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"} The Code For Django: from django.http import HttpResponse def index(request): return HttpResponse("Hello, world") I constantly read online, about FastAPI being asynchronous and I expected FastAPI to perform better than Django since it runs on one thread. And I got the opposite results. With this small application, Django outperformed FastAPI. I benchmarked this using locust, spawning 300 users while each user is making get requests. (though for different parameters I got similar results and Django performed even better) The locustfile.py code is: from locust import HttpUser, task class QuickstartUser(HttpUser): @task def hello_world(self): for i in range(1): print("sending reqeust") self.client.get("/") Attaching here the results Django (port 8000) FastApi (port 3636) Can someone please explain those results? Did I do something wrong with my benchmark? Thanks a lot, would appreciate some guidance here! -
Prefetch_related many to many
I need your help. I have two models with manytomany relationship, I'm using prefetch_related but I'm having some problems trying to render the QuerySet in the template. My question is, how can I show the data in the html file. The models: class Book(models.Model): name = models.CharField(max_length=300) price = models.IntegerField(default=0) class Store(models.Model): name = models.CharField(max_length=300) books = models.ManyToManyField(Book) class Meta: default_related_name = 'stores' The view: def mtmtest(request): books = Book.objects.prefetch_related('stores').all() return render(request, 'mtm.html', {'books': books}) -
Is there a way to control the formset properly?
I have a web which has the following form as shown in the pic below. Its basically a formset which is control by a button to limit the no. of form created or remove whatever form that is not needed. So whenever i clone the formset. It will appear as form-(number)-(fieldname). I have a '-' button which has the codes to reduce the number by 1. $(document).on('click', '#removerow', function () { let totalForms = $('#id_form-TOTAL_FORMS').val(); let actualformcount = totalForms-2; $('#id_form-TOTAL_FORMS').attr('value', (parseInt (totalForms))-1); $(this).closest('#morerows .row').remove(); if(actualformcount < maxrow){ $('#addrow').attr("disabled", false) $('#addrow').attr("class","btn btn-outline-success btn-rounded") $('#addrow i').attr("class","dripicons-plus") $('#addrow').html("+") } The above codes work for this image: Working as intended for delete of last row More about this 1st image: If i clone to the max limit i set and i delete the last row (circle in red). The ones that are circle in blue get saved to my database. But if i change the way i delete. I delete the 2nd clone (circle in blue this time), the ones that are circle in red this time get saved to database. But the last row does not get saved: Not working as intended for delete of any row other than last row Can anyone … -
Django - Test endpoints with authentication
How do you test endpoints in Django and ensure they have a valid JWT token when making a request? I'm using AWS cognito and amplify. I have these tests below and all these endpoints require user auth. Is there a way to generate a fake user token using AWS cognito or amplify during test then pass it when running these tests? tests.py class PostTest(TestCase): @classmethod # Generates Test DB data to persist throughout all tests def setUpTestData(cls) -> None: GoalCategory.objects.create(category='other', emoji_url='url') cls.user = UserFactory() cls.goal = GoalFactory() def test_create(self): response = self.client.post(reverse('post'), data=json.dumps({'creator_id': str(self.user.uuid), 'goal_id': str(self.goal.uuid), 'body': 'Some text #Test'}), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_improper_goal(self): response = self.client.post(reverse('post'), data=json.dumps({'creator_id': str(self.user.uuid), 'goal_id': 'some messed up UUID', 'body': 'Some text #Test'}), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) all the above requests being tested have token = request.META['HTTP_AUTHORIZATION'].split(' ')[1] print(token) try: res = jwt.decode_cognito_jwt(token) except: return Response("Invalid JWT", status=status.HTTP_401_UNAUTHORIZED) -
Linkedin OAuth works for http but not for https, Django app
LinkedIn OAuth works fine with http://example.com but after encrypting the site, it didn't work. It returns 'internal server error'. The stack is Django/Python. avatar_url = None if request.user.social_auth.filter(provider='linkedin-oauth2'): access_token = request.user.social_auth.get(provider='linkedin-oauth2').extra_data['access_token'] response = requests.get( 'https://api.linkedin.com/v2/me?projection=(id,profilePicture(displayImage~:playableStreams))', headers = {'Authorization': 'Bearer {}'.format(access_token)} ) avatar_url = response.json()['profilePicture']['displayImage~']['elements'][1]['identifiers'][0]['identifier'] The snapshot is standard for Django calling the auth. What seems wrong here? Any clue? -
Best practice in creating multiple related objects in Django
I am working with the Party domain model from the data model resource book. To illustrate the case a simplified version of the models is bellow. When an organization is a customer for example. I would be creating a combination of (Party, Organization, Role(type=customer), Customer) models. This is relatively a simple task. though where would this logic usually go. 1- A simple function from module import create_organization_customer. This method is relatively popular for advocates of the service pattern. Though it doesn't feel Django like. 2- Inside a Form ModelForm.save() or Form.create(). I like this but then adding rest_framework. would have me copy the logic to the Serializer.create(). etc.. 3- Inside a Manager Customer.objects.create() or customer.objects.create_customer(). This one is clean and feels more like how Django do things. though, I'm not sure how to feel about it when it spans beyond the Queryset boundaries. 4- Override Save on the Model Customer.save(). I think this is a popular solution. though I'm not sure its the cleanest. class Party(models.Model): party_id = models.CharField(max_length=100, unique=True) class Person(models.Model): party = models.OnetoOneField(Party, related_name="person", primary_key=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) class Organization(models.Model): party = models.OnetoOneField(Party, related_name="organization", primary_key=True, on_delete=models.CASCADE) legal_name = models.CharField(max_length=255) class Role(models.Model): class TypeChoices(models.TextChoices): CUSTOMER … -
Django - Iterating over list in template
Currently trying to iterate over a list using Django templating. What I am trying to achieve is having multiple row with three columns. The current logic creates a one row with around every third card element. What would be the best approach for creating each row w/ three columns? {% extends "stockwatcher/base.html" %} {% block content %} <div class="container"> {% for stock in stocks %} {% if forloop.counter0 == 0 or forloop.counter0|divisibleby:3 %} <div class="row"> {% endif %} <div class="col-sm"> <div class="card text-white bg-info mb-3" style="max-width: 18rem;"> <div class="card-header">{{stock.transaction_date}}</div> <div class="card-body"> <h5 class="card-title">{{ stock.id }} {{stock.ticker}} </h5> <p class="card-text">{{stock.senator}} - {{stock.type}}</p> </div> </div> </div> {% if forloop.counter0 == 0 or forloop.counter0|divisibleby:3 %} </div> {% endif %} {% endfor %} </div> {% endblock content %} -
Django - Write a test function that runs once before all test cases
I have this code here that creates entries in the table because they're required in order to create a new post. You need a user and a goal and goal category. I heard setUp() runs before every test so that's an issue as it could try to great instances that already exists. I'd like to run setUp() once before all the tests are run. How do I do this? class PostTest(TestCase): def setUp(self) -> None: GoalCategory.objects.create(category='other', emoji_url='url') self.user = UserFactory() self.goal = GoalFactory() def test_create_post(self): response = self.client.post(reverse('post'), data=json.dumps({'creator_id': str(self.user.uuid), 'goal_id': str(self.goal.uuid), 'body': 'Some text #Test'}), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_no_goal_create_post(self): response = self.client.post(reverse('post'), data=json.dumps({'creator_id': str(self.user.uuid), 'goal_id': 'some messed up UUID', 'body': 'Some text #Test'}), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_no_user_create_post(self): response = self.client.post(reverse('post'), data=json.dumps({'creator_id': 'messed up user', 'goal_id': str(self.goal.uuid), 'body': 'Some text #Test'}), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) -
Boolean is setting when someone visits th page NOT in Background
I am building a Blog App and I am trying to implement a feature of expiring blog posts so a Boolean will set to False after 5 Days. I have successfully implemented the feature of setting the Boolean to False by adding a property in models.py BUT The problem is :- Boolean is setting to true when someone visits the page after the expiring time. I mean "If a post is older than 5 days then the Boolean will set to True until someone visits the page BUT Not in the Background" models.py from django.utils import timezone from datetime import timedelta class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') body = models.CharField(max_length=30,default='') is_expired = models.BooleanField(default=False) date_added = models.DateTimeField(auto_now_add=True) @property def expireBounty(self): if self.is_expired: if self.date_added < timezone.now() - timedelta(days=7): self.is_bountied = False self.save() I have also tried many times but it is still not updating in background. Any help would be much Appreciated. Thank You in Advance. -
Django: how to find which CHECK constraint failed
I am using django 3. sqlite database. I have a situation in which an an instance in one of my models will not save. I get an integrity error and "CHECK constraint failed", followed by the name of my model ("post" in my "press" app: press_post). I have looked this up, and i guess it means that a value for one of my fields is impossible? If someone can explain what it means more accurately and precisely, it would be helpful. Mostly, I want to know how to find out which check constraint failed so I can fix it (which field or which piece of data in the model is causing the problem). other instances in the model save without any issues, while a few others have the same problem as this instance. I can access the instance in shell_plus and look at the data. it looks ok ... but obviously i'm missing something. the error output: --------------------------------------------------------------------------- IntegrityError Traceback (most recent call last) ~/pastrami/rye/lib/python3.8/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args) 83 else: ---> 84 return self.cursor.execute(sql, params) 85 ~/pastrami/rye/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py in execute(self, query, params) 422 query = self.convert_query(query) --> 423 return Database.Cursor.execute(self, query, params) 424 IntegrityError: CHECK constraint failed: press_post The … -
Models not appearing in Django Admin
I'm trying to register a model into Django-Admin and display and sort it in a different format and I've encountered two issues. when I'm on the add form I only see 1 other model instead of two (household < family w/ household PK < resident w/ family PK). when I'm all done with adding, they don't show up in the model list. model classes from model.py : class Household(models.Model): household_name = models.CharField(max_length=50, default='') number_of_members = models.IntegerField(default=1) street = models.CharField(max_length=50, default='') city = models.CharField(max_length=50, default='') barangay = models.CharField(max_length=50, default='') province = models.CharField(max_length=50, default='') monthly_income = models.FloatField(default=0.00) has_received_assistance = models.BooleanField(default=False) def __str__(self): return self.household_name def address(self): return self.street + ' ' + self.barangay + ' ' + self.city + ' ' + self.province def save(self, *args, **kwargs): doc_ref = db.collection('Household').document(self.pk) doc_ref.set({ u'household_name': self.household_name, u'number_of_members': self.number_of_members, u'street': self.street, u'city': self.city, u'barangay': self.barangay, u'province': self.province, u'monthly_income': self.monthly_income, u'has_received_assistance': self.has_received_assistance }) def delete(self, *args, **kwargs): FirestoreDelete('Household', self.pk) class Family(models.Model): household_group = models.ForeignKey(Household, on_delete=CASCADE, null=True) household_id = Household.pk family_name = models.CharField(max_length=50, default='') def __str__(self) -> str: return self.family_name def save(self, *args, **kwargs): doc_ref = db.collection(u'Family').document(self.pk) doc_ref.set({ u'household_id': self.household_id, u'family_name': self.family_name }) def delete(self, *args, **kwargs): FirestoreDelete('Family', self.pk) class Resident(models.Model): family_group = models.ForeignKey(Family, on_delete=CASCADE, null=True) family_id = … -
Django-rest-framework + React Admin results in api issues
I am developing a project that uses django-rest for backend, postgresql for db and react-admin for frontend and firebase for auth. For the django views I used the generic ones (ListAPIView, RetrieveAPIView, ListCreateAPIView, RetrieveUpdateDeleteAPIView). The issues are the following: When I open the link from my backend server and test the api it works perfectly, but when I use the react localhost link - it loads the interface, it shows the data from the backend but it does not allow me to create, edit or delete new items from the UI. When editing, deleting from the UI I receive 404 but when I do it from backend its ok. When creating from the UI I receive 405 Method not allowed, but I do not have any permissions set up and I am logged in as admin. When I set permissions the react-admin kicks me out of my profile and when I try to login it says "session expired" and kicks me out again. Can you advise me something or at least tell me what am I missing here. Thank you for your time. -
Django list matching with if == statement
I'm hoping this is super simple. I just started playing around with Django for fun and have been playing around with making a search engine. I'm setting a temporary list in a views.py file so I set it like this: tempsearch_list = Name.objects.filter( Q(name__iexact='Name Not Found') ) Later in my code I want to see if it's the same as I originally set so I'm trying to do this: if tempsearch_list == 'Name Not Found': This never matches. Even if I put it as the next statement after I set it. What am I doing wrong here. This has to be super simple. I've been trying different things for more time than I'd like to admit. -
Django - instances
How can i use in my views instances from other class? For example in my views i have: MODELS class Projekt(models.Model): nazwa_projektu = models.CharField(max_length=200, unique=True) opis_projektu = models.TextField() wybor_projekt = models.CharField(max_length=100, choices=wybor_t_f, default="FALSZ") VIEWS def ProjektViewOptions(request, pk): profil = Profil.objects.get(user=request.user) projekt = Projekt.objects.get(id=pk) srodek = projekt.srodek_set.all form = OptionsForm(request.POST or None) template_name = 'viewOptionsProjekt.html' if request.method == "POST": if form.is_valid(): pro.wybor_projekt = 'PRAWDA' pro.save() opcje = form.save(commit=False) opcje.wlasciciel = profil opcje.projekt = projekt opcje.save() opcje.wybor = 'PRAWDA' form.save() I want to do that, if i create a new Project this project have a options "FALSZ" when I "POST" this options will turn into the "PRAWDA" I tried do : opcje.projekt.wybor_projekt = "PRAWDA" But this unfortunately dont work. I dont want full solution. I need a little direction. ;) -
Removing a personalized class inside the view.py - Django
here is my view.py. Despite the code is a little bit long, I'd like to remove the class Ibm() from inside the else element to a new file called Ibm_class.py. I tried to do that but I couldn't find any way! def index(request): if 'GET' == request.method: return render(request, 'auditoria_app/index.html') else: class Ibm(object): def __init__(self, i): self.numeroIbm = inputsCombo[get_column_letter(i) + str(10)].value self.nome = inputsCombo[get_column_letter(i) + str(11)].value self.cidade = inputsCombo[get_column_letter(i) + str(12)].value self.uf = inputsCombo[get_column_letter(i) + str(13)].value self.anosProjeto = inputsCombo[get_column_letter(i) + str(16)].value self.anosAlternativa = inputsDNCombo[get_column_letter(i) + str(14)].value if self.anosAlternativa is None: self.anosAlternativa = 0 self.tipoInvestimento = inputsCombo[get_column_letter(i) + str(21)].value self.tipoProposta = inputsCombo[get_column_letter(i) + str(24)].value self.inicioVigencia = inputsCombo[get_column_letter(i) + str(34)].value self.prazoContrato = inputsCombo[get_column_letter(i) + str(38)].value # gas station variables self.faixaMargem = inputsCombo[get_column_letter(i) + str(19)].value self.rebateTotalCI = 0 self.rebateTotalCB = 0 self.unitariaCI = 0 self.volumeMensalCI = inputsCombo[get_column_letter(i) + str(60)].value self.volumeMensalCB = inputsDNCombo[get_column_letter(i) + str(32)].value self.margemCurva = inputsCombo[get_column_letter(i) + str(67)].value * 1000 self.margemCI = [] self.margemCB = [] self.volume12m = 0 self.margem12m = 0 self.curvaPostoCI = [] self.curvaPostoCB = [] self.rebateCI = [] self.rebateCB = [] self.faixaReal = '' self.volumeTotalCI = inputsCombo[get_column_letter(i) + str(151)].value self.volumeTotalCB = inputsDNCombo[get_column_letter(i) + str(121)].value # SELECT store variables self.feeIsencao = inputsCombo[get_column_letter(i) + str(220)].value self.feeFaturamento = inputsCombo[get_column_letter(i) + str(222)].value self.feeReal … -
Value too long for type character varying(x) though my string is within range
I am using phonenumber_field to store phone numbers. phone_number = PhoneNumberField(blank=False, max_length=12) I also just switched from sqlite db to postgres and also ran makemigrations and migrate. The sqlite db works but I keep getting this error "Value too long for type character varying(x)" for postgresql even though I am saving an instance with a string that is within the max_length requirement. These are my phonenumber_field settings PHONENUMBER_DB_FORMAT = "NATIONAL" PHONENUMBER_DEFAULT_REGION = "US" I create the object and save it to db # string length is 10 but settings above add "+1" to front when value is saved obj = User(..., phone_number='xxxxxxxxxx') obj.save() -
How to make responsive forms set in a for loop Django JavaScript
I am trying to make a form responsive to changes without refreshing the page with context. The forms are built in Django and the responsive behavior is coming from JavaScript. The forms are set in a for loop in HTML with Django Template Language. When the user loads the page, both form_one and form_two will be set to a blank option, with form_one being populated while form_two is yet to be populated. When the user changes the selection of form_one, form_two should then populate with the related context. If then the user changes again, the form will be reset and then populated with the related context. I can get the choices for either form in forms.py or views.py but I can't get the correct data or behavior in the template. forms.py class ExampleForm(forms.Form): form_one = forms.ChoiceField( widgets=forms.Select(attrs={'class': 'form-control'}, label='One', required=False, choices=[] ) form_two= forms.ChoiceField( widgets=forms.Select(attrs={'class': 'form-control'}, label='Two', required=False, choices=[(None, '')] ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs): logic to build form_one choices views.py def example_view(request): logic to build form_two choices # if condition 1, k = form_one_id, v = {form_two_id: form_two_name} # elif condition 2, k = form_one_id, v = {form_two_id: form_two_name} # elif condition 3, k = form_two_id, v … -
pip3 not found in Docker Alpine
I'm brand new to Docker and have been trying to containerize my Django application. Whenever I run docker-compose up, I get: => ERROR [ 6/15] RUN pip3 install -r requirements.txt 0.2s ------ > [ 6/15] RUN pip3 install -r requirements.txt: #10 0.207 /bin/sh: pip3: not found Dockerfile FROM python:3.9-alpine # Add scripts to PATH of running container ENV PATH='/scripts:${PATH}:/sbin' # Packages required on alpine in order to install uWSGI server used to run # Django application in production RUN apk update RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers RUN apk add python3 RUN apk add py3-pip RUN pip3 install -r requirements.txt I ran docker run -i -t alpine /bin/sh in my shell and, when I ran apk add python3, I verified that it does not provide pip, so I install pip and tried pip install ... and it successfully installed package. However, these commands do not seem to work in my Dockerfile. How can I fix this? I have tried running pip install, pip3 install, py-pip install, and py3-pip install, and nothing works. -
Celery shared tasks hang until a normal task is run
I'm working with Celery and Django. I have two tasks: @app.task(bind=True) def debug_normal_task(self): print('Hello World') @shared_task(bind=True) def debug_shared_task(self): print('Hello World') Whenever I try to run debug_shared_task, Celery hangs indefinitely, every time. It does this until I run debug_normal_task once. As soon as I run debug_normal_task, debug_shared_task starts working perfectly, every time. The same goes with every single one of my shared tasks project-wide. None of them work -> I run a single normal task anywhere -> all of them work. I could switch all of them to normal tasks, or just run a normal task when the project starts, but I'd like to understand why it's behaving this way to begin with. Here are the files involved: views.py from ceom.celery import debug_normal_task, debug_shared_task def news(request): debug_shared_task.delay() #Doesn't work debug_normal_task.delay() debug_shared_task.delay() #Works ... celery.py from __future__ import absolute_import import os from celery import Celery, shared_task from celery.schedules import crontab from ceom.celeryq.tasks_periodic import update_datasets os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ceom.settings") app = Celery("ceom") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() @app.task(bind=True) def debug_normal_task(self): print('Hello World') @shared_task(bind=True) def debug_shared_task(self): print('Hello World') __init__.py from __future__ import absolute_import from ceom.celery import app as celery_app __all__ = ('celery_app',) I'll admit I don't really know exactly what __init__.py does here. I got it from here. … -
Django and Timezones - Use same time across timezones
Okay. I've read a bunch of other answers, but none of them seem to be doing what I need to do. I need some help with times and dates. So I have an app such that the dates and times need to be based on the user's local time, but not change when the user changes time zones. For example, say a user is in New York. The app needs to show the local time in New York. Then the user can save a particular date and time that they want to timestamp. All in New York time. To be more specific, they load the page at it shows 10:32 am which is the local time in New York, then they can log dates and times, say 1 pm local time in New York on Sept 3 (a week from the day they are logging). But then that same user goes to Korea and they load the page. It now shows the local time in Korea, but the logged time now shows as Sept 3rd at 1 pm Korea time (not the equivalent of 1 pm in NY). So I need to show local time based on the current timezone, … -
return a custom data for a field in django ORM
I want to query an object that has a Char field which I is to be returned with correct datatypes for the corresponding values, upon every orm call for the object. For instance, class A(models.Model): tweet = models.CharField(max_length=120, default=dict) So, >>> a = A.objects.first() >>> a.tweet >>> {'x': '1'} This should return, instead: {'x': 1} For some reason, I don't want to save the field the way I expect it to be queried. Thanks in advance -
APIClient headers for testing
I'm working with django rest_framework and consuming an API that brings a header value to validate the sender. I have the problem when I use APIClient to test the webhook that I made. @pytest.mark.django_db def test_change_status_webhook_ok(webhook_client, status_changes): fixture_signature = ( "51b93156c361bfce14c527ddcb27cc3791e9ea6ede23bc5a56efa3be28e6a54d" ) url = reverse("webhook_v1:notification") response = webhook_client.post( url, json.dumps(status_changes), content_type="application/json", **{"X-Extserv-Signature": fixture_signature} ) assert response.status_code == 200 The problem is when I tried to get the X-Extserv-Signature from headers. I tried with: ret = request.headers.get("X-Extserv-Signature") this way only works when I receive a request from postman.. but the below form works when I do the request from APIClient and cannot get the value using the same above code. ret = request.META["X-Extserv-Signature"] You know how I can set the X-Extserv-Signature key value to headers in APIClient? -
Running uWSGI process not ending
I am having trouble with the running uWSGI workes, I cannot seem to stop them. Whenever I update a file in Django I used the uwsgi --ini [name]_uwsgi.ini command and it keeps running new workers . How can I kill old ones? I tried using killall uWSGI but it doesn't work. -
Django query on hierarchical models (Designing permission scopes)
I'm trying to design a set of scopes for permissions using Django models. Similar to groups but with different motive in mind. Side Note 1: I'm not sure if django-mptt is a solution to my problem or not. As I have different related models I guess it's not. Side Note 2: I can't use Django's group as I'm using them as roles (basically to group permissions together). Imagine that I have Paris and Berlin as my Cities, Art_school with Paris as the parent and Engineering_school with Berlin as its parent. Each school can have any number of classes. And using generic foreign key on User model, each user can be in one of these entities. Whats the purpose of this design? (I'm trying to create some scope for permissions). Anyone in a city with add_user permission can add users to that city, schools and all classes under that city. Anyone in a school with add_user permission can add users to that school and all classes under that school. Anyone in a class with add_user permission can only add users to that class. Same goes for other kind of permissions: add_school, add_class, remove_whatever, etc. What I'm looking for: Using an entity … -
Django foreign key mismatch when running migrations for polymorphic relationship
I have the following models in a Django app: class Sender(PolymorphicModel): name = models.CharField(max_length=100) email = models.EmailField(null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) class Student(Sender): group_name = models.CharField(max_length=100, null=True) class Teacher(Sender): bio = models.TextField(max_length=255, null=True) class Connection(models.Model): student_id = models.ForeignKey('students.Student', null=False, on_delete=models.CASCADE) teacher_id = models.ForeignKey('teachers.Teacher', null=False, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) class Message(models.Model): body = models.TextField(max_length=255, null=False) sender_id = models.ForeignKey('senders.Sender', null=False, on_delete=models.CASCADE) connection_id = models.ForeignKey('connections.Connection', null=False, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) Teacher and Student model classes both inherit from Sender; I want Connection to have specific foreign keys to Teacher and Student respectively. When I generate and run migrations, I get django.db.utils.OperationalError: foreign key mismatch - "connections_connection" referencing "teachers_teacher". Am I unable to use a child model that inherits from a polymorphic model as a foreign key to another model? Is there a way to get around this, or a different paradigm I should be using? Thanks!