Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot access django development server without ssl using chrome
I setup a clean django project with: django-admin startproject newProject cd newProject python manage.py migrate python manage.py runserver January 29, 2019 - 00:30:02 Django version 2.1.2, using settings 'unchained.settings' Starting development server at http://127.0.0.1:8000/ And navigate to http://127.0.0.1:8000/ with Google-Chrome (71.0.3578.98): [29/Jan/2019 00:30:08] You're accessing the development server over HTTPS, but it only supports HTTP. [29/Jan/2019 00:30:08] code 400, message Bad request version ('ÊÊÀ+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x00') [29/Jan/2019 00:30:08] You're accessing the development server over HTTPS, but it only supports HTTP. So, at some point in the past I activated SSL with a totally unrelated project. And for some strange reason, chrome now expects HTTPS. I could probably fix it by deleting the browser cache, but I don't really want to loose all the data that is in there. How would you solve this? -
Posting a Form (User input) into a widget in the admin panel with Django
So I want to post my Form into the Django Admin panel ( into a widget ). I have already made & styled out my form in HTML & CSS, I just want to post that info to my database and be able to see it for myself in the admin panel in a widget or so, I just want to post the Form data. So I was wondering for the best way to do this - ANY SUGGESTIONS? I want to: Post the user input to the Django Admin panel widget My current form looks like this - (I'm using Bootstrap 4, Django VERSION 2, 1, 1 ) Database: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } HTML: <div class="row"> <div class="col-sm-4"></div> <div class="col-sm-4"> <form method="post"> {% csrf_token %} <select class="custom-select custom-select-lg mb-3" name="typeoflocation" type="text" id="DropdownMenu"> <option selected>What type of a location is it?</option> <option value="1">Restaurant</option> <option value="2">Bar</option> <option value="3">Office</option> <option value="4">Hotel</option> <option value="5">Other</option> </select> <select class="custom-select custom-select-lg mb-3" name="location" type="text" id="DropdownMenu"> <option selected>In which city is your location?</option> <option value="1">Melbourne</option> <option value="2">Sydney</option> <option value="3">Canberra</option> </select> <div class="form-group"> <input type="text" class="form-control" id="formGroupExampleInput" name="nameoftheplace" placeholder="WHAT IS THE NAME OF THE LOCATION?"> </div> <div class="form-group"> <input type="text" … -
How to make custom template filter case insensitive? (Django 2.1)
My custom template filter highlights keyword put into my search engine in the results page, just like on Google. Search engine code: def query_search(request): articles = cross_currents.objects.all() search_term = '' if 'keyword' in request.GET: search_term = request.GET['keyword'] articles = articles.annotate(similarity=Greatest(TrigramSimilarity('Title', search_term), TrigramSimilarity('Content', search_term))).filter(similarity__gte=0.03).order_by('-similarity') context = {'articles': articles, 'search_term': search_term} return render(request, 'query_search.html', context) Custom filter code: register = template.Library() @register.filter(needs_autoescape=True) @stringfilter def highlight(value, search_term, autoescape=True): return mark_safe(value.replace(search_term, "<span class='highlight'>%s</span>" % search_term)) HTML template: <ul> {% for article in articles %} <li><a href="{% url 'search:article_detail' article.ArticleID %}">{{ article|highlight:search_term }}</a></li> <p> {{ article.Content|highlight:search_term|truncatewords:2000 }} </p> {% endfor %} </ul> The result is that the filter only highlights the text that exactly matches the case of the input keyword. If the user types "korean war", the filter will not highlight "Korean War". How can I make my filter case insensitive? -
config is not defined ,deploying in heroku
I am trying to deploy my django app on heroku ,I want to use remote postgre on heroku as well. dj-database-url is defined my requirement file which I have imported in setting.py as well . requirements.txt dj-database-url gunicorn Babel==2.6.0 settings.py import dj_database_url DATABASES = { 'default': dj_database_url.config( default=config('DATABASE_URL') ) } While deploying I have the below error ,anything I miss here ? "NameError: name 'config' is not defined" File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/build_b158ddc41a15ba9cab330674e51f4eff/restful01/settings.py", line 103, in <module> default=config('DATABASE_URL') NameError: name 'config' is not defined ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ! Push rejected, failed to compile Python app. ! Push failed -
Django importing db.json database dump error
I am trying to import part of the database from my dev environment to my production environment. I am dumping the data using this command: python3 local.py dumpdata --natural-foreign --indent=4 -e contenttypes -e auth.Permission -e sessions > db.json I receive the error at the bottom when I run this command: python3 production.py loaddata db.json I am starting with a clean new database that has been migrated, but I receive an error related to a duplicate user_id. When I search through django admin, it is empty after I remove the user I am logged in with. django.db.utils.IntegrityError: Problem installing fixture '/home/projects/stemletics/stemletics/mysite/db.json': Could not load memberships.UserMembership(pk=1): duplicate key value violates unique constraint "memberships_usermembership_user_id_key" DETAIL: Key (user_id)=(2) already exists. Should I use dbshell to drop that user_id table? -
2019: Dynamic cron jobs Google App Engine
I am developing a reporting service (i.e. Database reports via email) for a project on Google App Engine, naturally using the Google Cloud Platform. I am using Python and Django but I feel that may unimportant to my question specifically. I want to be able to allow users of my application schedule specific cron reports to send off at specified times of the day. I know this is completely possible by running a cron in GAE on a minute-by-minute basis and providing the logic to determine which reports to run in whatever view I decide to make the cron hit, but this seems terribly inefficient to me, and seeing as the best answer I have found suggests doing the same thing (Adding dynamic cron jobs to GAE), I wanted an "updated" suggestion. Is there at this point in time a better option than running a cron every minute and checking a DB full of client entries to determine which report to fire off? -
Django install and enviroment are no longer recognized
I just went to run my Django development server in the Django project that I'm working on and I got this... (baseballwebenv) C:\DjangoProjects\BaseballWebsite\baseballweb>python manage.py runserver Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "C:\Users\Nick\Anaconda3\envs\baseballwebenv\lib\site- packages\django\__init__.py", line 1, in <module> from django.utils.version import get_version File "C:\Users\Nick\Anaconda3\envs\baseballwebenv\lib\site- packages\django\utils\version.py", line 4, in <module> import subprocess File "c:\users\nick\anaconda3\Lib\subprocess.py", line 178, in <module> from _winapi import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP, ImportError: cannot import name 'ABOVE_NORMAL_PRIORITY_CLASS' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in <module> ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? As you can see I am by my runserver command, I am in my virtual environment. I recently upgraded all of my Anaconda packages, thinking everything was protected in the virtual environment. I would suspect this problem is related to that, but I'm not sure. How do I get my project up and running again? If someone wants to see certain files, I can add those as well. -
Folium map not displaying in Django webpage
Very new to Django (and web development in general), so apologies in advance. I'm trying to display my Folium map in a Django webpage, but I can't seem to figure out why I end up getting a blank screen. I looked for other posts in SO, but they're all asking for either the pop-ups specifically or displaying in Jupyter. views.py from django.shortcuts import render, redirect, render_to_response from django.http import HttpResponse from django.template.loader import get_template from django.template.context import RequestContext import pandas as pd import folium def folium_map(request): coords = [(40.7831, -73.9712), (40.6782, -73.9412), (40.7282, -73.7949)] map = folium.Map(location=[40.7118, -74.0131], zoom_start=12) for coord in coords: folium.Marker(location=[coord[0], coord[1]]).add_to(map) context = {'map': map} return render(request, 'template.html', context) Then, in my template.html file, I just try to insert the map in a div tag: <div> {{ map|safe }} </div> And it's blank. Do I need an Iframe? Is there a script source I should be running that allows for leaflet maps? How do I set it up, since I need a source? Would I have to save the map as an html file locally, because I'm trying to get this deployed so other people can use it, and if it's the case where each time … -
How to populate partially a formset in Django
I’m having difficulty pre-populating only some fields in a model formset. For context, the project is an attendance app where there will be a grid with columns:the students name,the date,and if the student is present or not. The goal is that the column with the students name is filled with all the students names(already saved in Database from the student model),and that the date is the same for all the rows.So that when the user is going to take attendance,he only has to click in the checkbox of the attendance. I've found a question similar to mine,but it was not answered. If needed,I can post my codes for help. Any help will be much appreciated. -
Reference individual field of model in another model?
I have three models so far: class clientCode(models.Model): unique_id = models.CharField(max_length=9, blank=False) def __str__(self): return self.unique_id class clientAccount(models.Model): clientCode = models.ForeignKey(ClientCode, on_delete=models.CASCADE, related_name='clientBusiness', null=True) clientAccount = models.CharField(max_length=13,blank=False) clientName = models.CharField(max_length=45,blank=False) class assets(models.Model): assetName = models.CharField(max_length=45,blank=False) assetCurrency = models.CharField(max_length=45,blank=False) assetCode = models.CharField(max_length=15,blank=False) def __str__(self): return self.assetName Now, I would like to have a model containing ALL the fields from the above + an amount and transaction. I started as so... class Holdings(models.Model): holdingsName = models.ManyToManyField(assets) The issue is this, while this returns the assetName which is what I'd like, how do I retrieve the assetCurrency? I guess I need to know: How do I reference an individual field from one model another model? I am truly lost on how to do this, i've tried various ForeignKey, ManytoMany.. Is the correct approach to build a form that includes all the fields and posts to said model? Sorry if this is unclear and thanks in advance for any help! - I'm sure Ive got the wrong end of the stick on how to build the models. -
Detect HttpResponseRedirect and Get Header Data in Django?
I'm trying to capture an HttpResponseRedirect from a render within a function. I have some success... but I want to be able to extract the Location. For Example.. {'content-type': ('Content-Type', 'text/html; charset=utf-8'), 'location': ('Location', '/app/create/preview/')} Is a response that I'm able to get using xxx_response._headers How do I decode this? Can someone please point me in the right direction? Thank you. -
MultiValueDictKeyError in django 1.11.18
I am using Python 3.7 with Django 1.11.18. I have to connect to an Oracle 11g database and that is why the use of 1.11 version for django. The below code was working for django 2.0.7 and python 3.7 but when i downgraded my version to 1.11.18 it s started giving me the error. I am sending a post request via an HTML form. The post request has fields username and password. The python code to retrieve the same is :- username = request.POST[‘username’] password = request.POST[‘password’] I also tried username = request.POST.get(‘username’, False) The above code picks up the default value even though a valid valuse is passed through my form. Any idea why this is happening and how to solve it. -
Collapsed fixed-top bootstrap 4 menu not staying open
I'm using bootstrap 4 for a wagtail CMS/django site. It's a fixed-top nav that collapses on mobile using the hamburger menu. When I click on the hamburger menu, it opens, but then immediately closes. What am I missing to get the menu to stay open? I've looked on stack overflow and wagtail doesn't provide much in the way of troubleshooting. I double checked my code against other example code on the bootstrap site. <nav class="navbar navbar-fixed-top navbar-expand-lg navbar-light" role="navigation"> <div class="container-fluid"> <a class="navbar-brand" href="{% slugurl 'home' %}"><img src="{% static "images/logo_R_long_invert.png" %}" height="100%" class="img-fluid" alt="The Ringlwald Theatre"></a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> {% main_menu max_levels=2 use_specific=USE_SPECIFIC_TOP_LEVEL template="menu/main_menu.html" %} </div> </div> </nav> -
Running python3 manage.py runserver but not seeing any requests
I activated my environment with source env/bin/activate Then, I started my server at python3 manage.py runserver 0.0.0.0:80 I have made sure to add ALLOWED_HOSTS = ['xx.xx.xx.xxx', 'mywebsite.org'] to settings.py I start the server and it outputs : System check identified no issues (0 silenced). January 28, 2019 - 21:40:33 Django version 2.0.7, using settings 'app.settings' Starting development server at http://0.0.0.0:80/ Quit the server with CONTROL-C. But, I visit "mywebsite.org" and it outputs > Index of / > Name Last modified Size Description cgi-bin > 2018-08-23 07:26 - The homepage of my website normally appears when I visit "http://127.0.0.1:8000/", so how can I get that to appear? -
Is there a way to create a multiple-item text input in html?
I'm looking to find/create some sort of html text input field where users can input multiple items. This could either be in one text box (but ideally with a clear distinction between items) or through multiple boxes, though the number of boxes should be variable. I can probably write something that achieves the latter, but I was wondering if anything already existed. The result would be passed to a Django-based web app as a Python list, if that changes anything. Push comes to shove I'll simply instruct users to enter all items in one text box delimited by commas. -
getting urllib3.exceptions.ProtocolError: ('Connection aborted.', ConnectionResetErr or(104, 'Connection reset by peer'))
I have setup a Django project with Apache2 and mod_wsgi on Ubuntu 16.04 instance of AWS. Now I am getting urllib3.exceptions.ProtocolError: ('Connection aborted.', ConnectionResetErr or(104, 'Connection reset by peer')) error when I try to access mysite. I have tried almost everything suggested on stackoverflow and other link. but get no luck. [Mon Jan 28 21:02:52.263398 2019] [wsgi:error] [pid 27292:tid 140652916205312] [remote 172.31.25.223:61898] Traceback (most recent call last): [Mon Jan 28 21:02:52.263457 2019] [wsgi:error] [pid 27292:tid 140652916205312] [remote 172.31.25.223:61898] File "/var/www/env/lib/python3.6/site-packages/urllib3/connectionpool.py", line 600, in urlopen [Mon Jan 28 21:02:52.263537 2019] [wsgi:error] [pid 27292:tid 140652916205312] [remote 172.31.25.223:61898] chunked=chunked) [Mon Jan 28 21:02:52.263613 2019] [wsgi:error] [pid 27292:tid 140652916205312] [remote 172.31.25.223:61898] File "/var/www/env/lib/python3.6/site-packages/urllib3/connectionpool.py", line 384, in _make_request [Mon Jan 28 21:02:52.263655 2019] [wsgi:error] [pid 27292:tid 140652916205312] [remote 172.31.25.223:61898] six.raise_from(e, None) [Mon Jan 28 21:02:52.263707 2019] [wsgi:error] [pid 27292:tid 140652916205312] [remote 172.31.25.223:61898] File "", line 2, in raise_from [Mon Jan 28 21:02:52.263760 2019] [wsgi:error] [pid 27292:tid 140652916205312] [remote 172.31.25.223:61898] File "/var/www/env/lib/python3.6/site-packages/urllib3/connectionpool.py", line 380, in _make_request [Mon Jan 28 21:02:52.263799 2019] [wsgi:error] [pid 27292:tid 140652916205312] [remote 172.31.25.223:61898] httplib_response = conn.getresponse() [Mon Jan 28 21:02:52.263851 2019] [wsgi:error] [pid 27292:tid 140652916205312] [remote 172.31.25.223:61898] File "/usr/lib/python3.6/http/client.py", line 1331, in getresponse [Mon Jan 28 21:02:52.263903 2019] [wsgi:error] [pid 27292:tid 140652916205312] … -
django-leaflet place table element on map
I have a Django application that manages a physical network. The network has 5 types of elements which are stored in an "element" table with PostgreSQL. I am now trying to update the application with a Geographical Information System (GIS). The goal is to view the network (at least in a basic "where is what" way, next step would be to color elements according to usage, etc). I have started using Leaflet with its draw plugin. The elements fit the basic drawing tools (point / line / area). I need help on how to link the elements. I have the elements table below the map, but I do not know how to say "this element is what I am drawing right now". The objective would be to click on elements that do not have a location and have the right drawing form (e.g.: "Type A" draws a "line", "Type B" draws a "point"). If the element is already on the map, then we could edit it. Some users would be able to modify an element, some would only have the right to view the map. I use DataTables which contacts the server's custom API. If Leaflet is not the right … -
Get all field names in a Django form in python view
How to get all field names in a Django non-model form inside python views.py file. -
Django CBV UpdateView not saving form to database. (Django 2.0)
I am new to django and currently working on a side project. I have two models User and Profile which have one to one relationship. I have created post_save signal so when the a new user signs up, his empty profile instance is already created in the database. def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) post_save.connect(create_profile, sender=CustomUser) Since the profile is already created, I thought why not skip the CreateView and use UpdateView to save the profile form. By doing that I just have to create one form for profile. So I have only one view that is UpdateView. When the user creates his account he is directed to the Profile(automatically created) form where he saves(updates) his information. Now when in updateView template when I submit the form, nothing is saved in the database, however form successfully saves via admin panel and also fields are being populated correctly from the database since it is an update form. What could be the problem? View class ProfileSettingsView(UpdateView): model = Profile form_class = ProfileSettingsForm pk_url_kwarg = 'pk' context_object_name = 'object' template_name = 'profile_settings.html' def get_object(self): pk = self.kwargs.get('pk') return get_object_or_404(Profile, id=pk) def get_context_data(self, **kwargs): c_object = self.get_object() context = super(ProfileSettingsView, self).get_context_data(**kwargs) context['linked_in'] … -
Can't connect to test server. "ERR_CONNECTION_REFUSED"
I'm new to Django and I'm trying to run test server by python3 manage.py runserver. I got information that everything went smoothly: Performing system checks... System check identified no issues (0 silenced). You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. January 28, 2019 - 19:15:50 Django version 2.1.5, using settings 'mytestsite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Still when I try to connect to http://127.0.0.1:8000/ from Chrome browser I got the information that website is unreachable. My firewall configuration on Ubuntu: Status: active Logging: on (low) Default: deny (incoming), allow (outgoing), disabled (routed) New profiles: skip To Action From -- ------ ---- 22/tcp (OpenSSH) ALLOW IN Anywhere 8000 ALLOW IN Anywhere Anywhere ALLOW IN 127.0.0.1 22/tcp (OpenSSH (v6)) ALLOW IN Anywhere (v6) 8000 (v6) ALLOW IN Anywhere (v6) What else might be wrong? It's my first setup. Thanks for help. -
Understanding use of Class inheritance and __init__ method
I have module for inserting data into Models from JSON data. Each Class takes care of inserting the data into the given model, and they all inherit the same class. The purpose of this one class is the url will be different for each model, so it made sense as to not rewrite code. class Data_config: def get_data_set(self, url): self.headers = urllib3.util.make_headers(basic_auth='conner.johnson:Mercy538478') self.url = url self.http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) self.request = self.http.request('GET', self.url, headers=self.headers) self.real_data = json.loads(self.request.data.decode('utf-8')) return self.real_data The Data_config class takes the url arguement given in the other classes like so class First_data(Data_config): def __init__(self): self.first_json = Data_config.get_data_set(self, '<url for First_data>') self.insert_epic_data(self.first_json) def insert_epic_data(data): values2 = list((item['key'], # key item['fields']['customfield_10009'], # name item['fields']['status']['name'] # status ) for item in data['issues']) for epic in values2: e = First(key=first[0], name=first[1], status=first[2]) e.save() class Second_data(Data_config): def __init__(self): self.second_json = Table_needs.get_data_set(self, '<url for Second_data>') self.insert_epic_data(self.second_json) def insert_epic_data(data): values2 = list((item['key'], # key item['fields']['customfield_10009'], # name item['fields']['status']['name'] # status ) for item in data['issues']) for epic in values2: e = Second(key=second[0], name=second[1], status=second[2]) e.save() I'm using the Django framework and the purpose of this is to make a call like First_data.__init__(First_data) in my views.py to insert data into the models. This above code … -
Ajax request to Django only succeeds if there is no sessionid cookie
I have sessions enabled in Django to use Django's authentication framework. From a html page served by Django, and after authenticating as a user with sufficient permissions, I'm trying to send a PATCH request via JQuery's ajax() function, and I'm getting HTTP 403 errors with the response detail CSRF Failed: CSRF token missing or incorrect. What I've done so far: I'm including the correct csrf token in the X-CSRF-TOKEN header field. I've set SESSION_COOKIE_HTTPONLY = False. The cookie sent in the ajax request includes the sessionid. If I get rid of this sessionid, the request succeeds.To do so, I either delete the session cookies in the browser or edit the PATCH request in the browser's developer tools and resend it with the sessionid deleted from the Cookie header field. Obviously I need to re-login as soon as I refresh the page, but in the meantime, I can PATCH to my heart's content. So far I couldn't find out why the presence of the sessionid cookie makes Django deny the request. -
Maths and Linear Algebra
I'm studying math and computer science in french's college, and this semester I'm learning Linear Algebra for the first time. I would like to know, how can I use my knowledge in Linear Algebra with Python and for what kind of uses? Is there any resources I can access to get better at both Linear algebra and python? Knowing that there is a real motivation behind Linear Algebra and Computer Science will make my study a 100 times better :) Sorry for my weak English :/ Thanks for helping and I wish everyone one a good evening! -
Django template loop through items with parent ID or PK
I'm trying to set up magnific popup on django. My goal is to have one main picture in the homepage overview gallery view, which when clicked, would open a popup with the related images from the same photoshoot i.e. images with the same ID or PK. I tried to apply the following approach but i just cannot get it to work, maybe someone could help me out in this My models.py class Item(models.Model): name = models.CharField(blank=False, max_length=200) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) order = models.IntegerField(blank=True, null=True) active = models.BooleanField(blank=True, default=False) objects = models.Manager() class Meta: verbose_name_plural = 'items' def __str__(self): return self.name class ItemImage(models.Model): image = ProcessedImageField( blank=True, null=True, processors=[ResizeToFit(width=1680, upscale=False)], format='JPEG', options={'quality':90}) order = models.IntegerField(blank=True, null=True) main = models.BooleanField(blank=True, default=False) cover = models.BooleanField(blank=True, default=False) item = models.ForeignKey(Item, related_name='items', blank=True, null=True, on_delete=models.SET_NULL) objects = models.Manager() class Meta: verbose_name_plural = 'item images' Views.py def portraits(request): port = ItemImage.objects.filter(item__category__slug='portraits', item__active=True, main=True,).order_by('item__order') portall = ItemImage.objects.filter(item__category__slug='portraits', item__active=True).order_by('item__order') context = { 'main_portraits': port, 'all_portraits': portall } return render(request, 'gallery/portraits.html', context) and Template: {% block content %} <div class="grid"> {% for pic in main_portraits %} <div class="item"> <div class="item"> <div class="outer-text"> <div class="text"> {{ pic.item.name }} <p>Click to view gallery</p> </div> </div> <a><img class="lazy" alt="" … -
Django Subquery, ORA-00904: invalid identifier
The query below works as raw sql SELECT WORK_ORDER.*,(SELECT COMPLETE FROM SAMPLE WHERE COMPLETE = 'TRUE' AND ARF_ID = WORK_ORDER.ARF_ID AND ROWNUM <= 1) AS SAMPLE_COMPLETE, (DUE_DATE - SYSDATE) AS DUE_IN FROM WORK_ORDER WHERE COMPLETE = 'FALSE' ORDER BY DUE_DATE ASC The following Django Queryset does not work subquery = Sample.objects.filter(complete = 'TRUE', arf_id = models.OuterRef('arf_id'))[:1] workOrderList = WorkOrder.objects.annotate(sample_complete= models.Subquery(subquery.values('complete'))).annotate(due_in= models.F('due_date') - datetime.now()).filter(complete = 'FALSE').order_by('due_date') which produces this query when running workOrderList.query SELECT "WORK_ORDER"."ARF_ID", "WORK_ORDER"."COMPANY_NAME", "WORK_ORDER"."COMPANY_ADDRESS", "WORK_ORDER"."CONTACT_TELEPHONE", "WORK_ORDER"."ORDER_DATE", "WORK_ORDER"."DUE_DATE", "WORK_ORDER"."ARF_NUMBER", "WORK_ORDER"."COMPLETE", "WORK_ORDER"."COMPLETE_DATE", "WORK_ORDER"."REPORTED", "WORK_ORDER"."REPORTED_DATE", "WORK_ORDER"."COMPANY_CODE", (SELECT * FROM (SELECT "_SUB".* FROM (SELECT U0."COMPLETE" AS Col1 FROM "SAMPLE" U0 WHERE (U0."COMPLETE" = TRUE AND U0."ARF_ID" = ("WORK_ORDER"."ARF_ID"))) "_SUB" WHERE ROWNUM <= 1)) AS "SAMPLE_COMPLETE", ("WORK_ORDER"."DUE_DATE" - 2019- 01-28 13:00:51.043013) AS "DUE_IN" FROM "WORK_ORDER" WHERE "WORK_ORDER"."COMPLETE" = FALSE ORDER BY "WORK_ORDER"."DUE_DATE" ASC This returns error cx_Oracle.DatabaseError: ORA-00904: "WORK_ORDER"."ARF_ID": invalid identifier I am using Django 1.11.13 and this is a legacy database, I am comfortable using raw sql to query data but would like to learn/utilize the Django ORM the correct way so any fix or explanation why this won't work is helpful to me.