Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
when i use the django can't loading picture only if remove "/" at the urls.py.why?
url(r'^detail', detail, name="detail"), this can loading it url(r'^detail/', detail, name="detail"), this can't loading the picture Somebody tell me why? thank you -
AttributeError: "addinfourl instance has no attribute '__getitem__'"
I am writing a Django command to get the json data from a URL and update the database with the values. Code - class Command(BaseCommand): args = 'Arguments is not needed' help = 'Django admin custom command poc.' def appmap_contacts(self): api_url = '<url>' try: logger.info('Reading data from %s'%api_url) request = urllib2.Request(api_url) response = urllib2.urlopen(request) self.update_data(response) except Exception as e: logging.error("Exception while parsing the json data " + str(e)) return def update_data(self, data): curr_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') import pdb; pdb.set_trace() try: update_status = None log_text = 'inside update_data function' logger.info(log_text) group_name = data["last_name"].upper() print group_name adminObj = Contacts.objects.get(first_name='', last_name='admin', userid='admin') contactObj = '' contactObj_filter = Contacts.objects.filter(last_name=group_name) if contactObj_filter.count() == 1: logger.info("update") contactObj = contactObj_filter[0] contactObj.status = 'Active' contactObj.modified_on = curr_date contactObj.modified_by_id = adminObj.contact_id contactObj.contact_type = 'group' contactObj.source = 'cmdb' update_status = 'UPDATED' elif contactObj_filter.count() == 0: logger.info("insert") contactObj = Contacts() contactObj.last_name = group_name contactObj.status = 'Active' contactObj.created_on = curr_date contactObj.modified_by_id = adminObj.contact_id contactObj.contact_type = 'group' contactObj.source = 'cmdb' update_status = 'INSERTED' else: contactObj = contactObj_filter[0] logger.info("WORKER :: Duplicate Contact Group Found"+str(group_name)) except Exception as e: logging.error("Exception while Insert Contacts to DB. Error is " + str(e)) return JSON Data format - {"meta": {"limit": 3391, "next": "", "offset": 0, "previous": "", "total_count": … -
Django Have all submit buttons go back to home page
I have an app with one main page that has several buttons. Each button performs some view functionality and then returns the main page. When the button below is clicked it returns that main page but the url says: http://localhost:8080/abc_app/backup_system. This creates some POST resend prompt/issue when I hit the browsers refresh button. Is there anyway for me to return http://localhost:8080/abc_app instead of http://localhost:8080/abc_app/backup_system? Thanks ahead of time. <form action="{% url 'abc_app:backup_system' %}" method="post">{% csrf_token %} <button type="submit" name="index" class="btn btn-primary btn-block float-right"value="index">Refresh</button> </form> -
Django FULL OUTER JOIN
I have these three tables class IdentificationAddress(models.Model): id_ident_address = models.AutoField(primary_key=True) ident = models.ForeignKey('Ident', models.DO_NOTHING, db_column='ident') address = models.TextField() time = models.DateTimeField() class Meta: managed = False db_table = 'identification_address' class IdentC(models.Model): id_ident = models.AutoField(primary_key=True) ident = models.TextField(unique=True) name = models.TextField() class Meta: managed = False db_table = 'ident_c' class location(models.Model): id_ident_loc = models.AutoField(primary_key=True) ident = models.ForeignKey('IdentC', models.DO_NOTHING, db_column='ident') loc_name = models.TextField() class Meta: managed = False db_table = 'location I want to get the last address field (It could be zero) from IdentificationAddress model, the last _loc_name_ field (it matches at least one) from location model, name field (Only one) from IdentC model and ident field. The search is base on ident field. I have been reading about many_to_many relationships and prefetch_related. But, they don't seem to be the best way to get these information. If a use SQL syntax, this instruction does the job: SELECT ident_c.name, ident_c.ident, identification_address.address, location.loc_name FROM identn_c FULL OUTER JOIN location ON ident_c.ident=location.ident FULL OUTER JOIN identification_address ON ident_c.ident=identification_address.ident; Based on my little understanding of Django, JOIN instructions cannot be implemented. Hope I am wrong. -
Deploying django on app engine 500 server error
I am trying to deploy completed web-app (runs locally) on the app engine. The app has no databases and the web page is static. My primary problem is that I try to deploy the app and I get a server error. I suspect that the issue lies with my app.yaml file but I cannot seem to fix it. Here is my yml file: runtime: python27 api_version: 1 threadsafe: yes handlers: - url: /static static_dir: personal/static/ - url: /.* script: mysite.wsgi.application The directory is organized so that the 'personal' is an installed app and static, templates etc. are inside the personal folder. -
Trouble adding background image to div in Django site
I want to add a background image to a div that is a row in Bootstrap in Django site. My CSS says: .bimage { background-image: url("{% static 'home/images/background.jpg' %}"); } I confirmed that the jpg is in the right folder. Could something else be wrong? -
django 1.11.3 css background image not showing
I am trying to have my background image show using css in django 1.11.3 and have received some 404 errors in the terminal when running the server that the picture can't load. My css file does load and can change the contents in my home.html file. home.html {% extends 'layout.html' %} {% load static %} {% block content %} <div class="container-fluid"> <div class="row img-bg"> <div class="col-sm-12"> <a href='#'>My Button</a> </div> </div> </div> CSS - .img-bg{ background: url('../img/logo.png'); // 404 error background: url('../assets/img/logo.png'); // 404 error background: url("{% static 'img/logo.png' %}"); // 404 error background-size: 100% auto; height: 100px; width: 100px; } settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) folder structure website_src --assets --css --style.css --img --logo.png -
Django Python OSError No such file or directory but file exists
I'm converting doc and docx files to pdf in the server using unoconv with LibreOffice. And I need to upload to S3 the converted file. I can convert with success the files and I can see them in the server. But when I try to upload the pdf, I get the error. What am I missing? Thanks in advance This works just fine: import subprocess from boto.s3.connection import S3Connection, Bucket, Key def doc_to_pdf(user): ''' Convert doc or docx to PDF. parameter user: is a request.user Usage: doc_to_pdf(self.request.user): ''' user_cv = CandidateCV.objects.get(user=user) user_cv_file = str(user_cv.resume).split('/')[-1] # tem que ser PDF user_cv_filetype = user_cv_file.split('.')[-1] if not user_cv_filetype in settings.PDF_FILE_TYPE: # Se não for PDF file_in = user_cv.resume.url file_name = file_in.split('/')[-1] # download urllib.request.urlretrieve(file_in, file_name) file_out = user_cv_file.split('.')[0] + '.pdf' # converte para PDF env = os.environ.copy() env['HOME'] = '/tmp' subprocess.Popen(["unoconv","-f", "pdf", "%s" % (file_in)], env = env) # Define a path para salvar o documento na S3 resume_path = 'resumes/%s/' % str(date.today()) # key é o nome do arquivo na S3 key = '%s%s' % (resume_path, file_out) # deleta o arquivo localmente subprocess.call("rm -f %s" % user_cv_file, shell=True) # Salva o novo formato no banco user_cv.resume = key user_cv.save() This is the … -
is there a way to add in more dict after inside an append? django
Apologize if the title is a bit hard to understand. Not too sure how to explain it within a line. What I want to do is... actually I have this code output = [] objs = Model.objects.filter(abc=abc) # this would return a some queryset for obj in objs: output.append({ TITLE: obj.title, TYPE: obj.type, # I want to add something here which is kind of like, if `obj.type` is 'hello' then print obj.word }) return output for example, if my obj.type is 'hello' I want output.append({ TITLE: obj.title, TYPE: obj.type, WORD: obj.word, }) if my obj.type is 'world' I want output.append({ TITLE: obj.title, TYPE: obj.type, NADA: obj.nada, }) I thought of doing something such as output = [] objs = Model.objects.filter(abc=abc) # this would return a some queryset for obj in objs: if obj.type == 'hello': output.append({ TITLE: obj.title, TYPE: obj.type, WORD: obj.word, }) if obj.type == 'world': output.append({ TITLE: obj.title, TYPE: obj.type, NADA: obj.nada, }) return output the above should work but if there is another better way, I would love to know another way of doing this because the above seems too redundant. Thanks in advance for any advices -
Using django-cassandra-engine sessions and getting a error
I'm using django-cassandra-engine for storage the sessions, when run the server I get this error: RuntimeError: Model class django.contrib.sessions.models.Session doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS The steps I followed are these link INSTALLED_APPS += ['django_cassandra_engine.sessions'] SESSION_BACKEND = 'django_cassandra_engine.sessions.backends.db' -
Django 1.11 Update Model with Class Based View
I need a way to change a single object field using a class based view in Django. My model has a display_order field which allows me to order the objects on the screen. On the template I want to click a single button that would call a view. This view will then update the display_order field by adding or subtracting. I tried various generic views without luck - my view needs to accept the pk argument, get the object from the database, update the field and reverse to the original page. I don't have any useful code to share as the standard generic views have limitations (e.g. requiring a template and not allowing automatic reverse to original page). Any assistance would be much appreciated! -
How to iterate over a bytes object in Python?
I am doing a POST request in Django and I am receiving a bytes object. I need to count the number of times a particular user appears on this object but I am receiving the following error TypeError: 'int' object is not subscriptable. This is what I have so far: def filter_url(user): ''' do the POST request, this code works ''' filters = {"filter": { "filters": [{ "field": "Issue_Status", "operator": "neq", "value": "Queued" }], "logic": "and"}} url = "http://10.61.202.98:8081/Dev/api/rows/cat/tickets?" response = requests.post(url, json=filters) return response def request_count(): '''This code requests a POST method and then it stores the result of all the data for user001 as a bytes object in the response variable. Afterwards, a call to the perform_count function is made to count the number of times that user user001 appeared.''' user = "user001" response = filter_url(user).text.encode('utf-8') weeks_of_data = [] weeks_of_data.append(perform_count(response)) def perform_count(response): ''' This code does not work, int object is not subscriptable ''' return Counter([k['user_id'] for k in response) #structure of the bytes object b'[{"id":1018002,"user_id":"user001","registered_first_time":"Yes", ...}]' # This is the result that indicates that response is a bytes object. print(type(response)) <class 'bytes'> How can I count the number of times that user001 appears by using the the … -
Getting VirtualEnvs to work in Eclipse
Arg! I know everyone is supposed to use virtualenv, but it has to be one of the most confusing tools to the programmer's toolkit (after git I suppose.) So, I created a virtualenv. Since I work off two different personal computers I put my local git repo into a OneDrive folder. OK, er, virtualenv folder also needs to be there. OK, move it into OnDrive also, cool. Not cool. Now eclipse is complaining it can't find the interpreter. OK, I redirect it to the Python.exe in the Ondrive's virtualenv folder. Still not cool? "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?" I give up. If I point it to the standard python.exe things generally work, but I just can't seem to get it to work with virtual envs. Am I doing something obviously wrong? -
Django Rest Framework: Adding a custom field to a paginated ViewSet
I have a paginated result set so the response comes back like this: { "count": 944, "next": "http://api.visitorlando.teeny/consumer/listings/?page=3", "previous": "http://api.visitorlando.teeny/consumer/listings/", "results": [ {...}] } I need to add another custom field to the Response like this: { "count": 944, "custom_field": "test", "next": "http://api.visitorlando.teeny/consumer/listings/?page=3", "previous": "http://api.visitorlando.teeny/consumer/listings/", "results": [ {...}] } and I am inside a ViewSet. How am I able to do this? -
Create website alone
Maybe it is not the good website for that question, but I'll try. I have seven months of experience in Django so far and I think it is sufficient to start working on individual project. I would like to find projects on the website which will pay well and I could do it alone. Is there exist a good website where people ask to code a website or an application in Django? I would like to be able to bid on that type of project. -
Custom PSA Auth doesn't appear to get called
I'm trying to make a custom backend auth for Python Social Auth for GoodReads. I've created the custom class and added it to the AUTHENTICATION_BACKENDS but when I call http://127.0.0.1:8000/login/goodreads/ It doesn't seem to do anything except a redirect. I've confirmed that the it does direct to the good reads authentication urls when I tried Authing from a private window (It asked me to login). I don't have any entry for goodreads in my DB and I've added a print statement to verify that the the user_data method is being called, which it never is. The Key/Secret are also correct. class GoodReadsOAuth(BaseOAuth1): """GoodReads OAuth authentication backend""" name = 'goodreads' AUTHORIZATION_URL = 'https://www.goodreads.com/oauth/authorize' REQUEST_TOKEN_URL = 'https://www.goodreads.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://www.goodreads.com/oauth/access_token' def get_user_details(self, response): """Return user details from GoodReads account""" return {'username': response['username']} def user_data(self, access_token, *args, **kwargs): """Return user data provided""" url = 'https://www.goodreads.com/api/auth_user' request = self.oauth_request(access_token, url) content = self.fetch_response(request) # content = self.oauth_request(access_token, url)._content dom = minidom.parseString(content) good_reads_id = dom.getElementsByTagName('GoodreadsResponse')[0] \ .getElementsByTagName('user')[0] \ .attributes['id'].value good_reads_username = dom.getElementsByTagName('GoodreadsResponse')[0] \ .getElementsByTagName('name')[0] \ .firstChild.nodeValue print { 'id': good_reads_id, 'username': good_reads_username, } return { 'id': good_reads_id, 'username': good_reads_username, } -
Not required many-to-many relationship giving ValueError
I'm having an issue where I have a non required self many-to-many relationship that when saving a new object gives me: ValueError: "Video: Teste" needs to have a value for field "from_video" before this many-to-many relationship can be used. This is my model: class Video(models.Model): title = models.CharField(max_length=200, unique=True) subtitle = models.CharField(max_length=400) thumbnail = models.ImageField(upload_to='videos/thumbnails') related_videos = models.ManyToManyField('self', symmetrical=False, blank=True) This is my save function: def save(self, *args, **kwargs): if self.id is None: # Elasticsearch document creation if word does not exist video = VideoDocType(title=self.title, subtitle=self.subtitle, thumbnail=str(self.thumbnail)) video.save() else: old_value = Video.objects.get(id=self.id) thumbnail_url = str(self.thumbnail) video = self._get_video(self) if video is None: video = VideoDocType(title=self.title, subtitle=self.subtitle, thumbnail=str(self.thumbnail)) video.save() else: if old_value.thumbnail != self.thumbnail: thumbnail_url = ("videos/thumbnails/" + thumbnail_url) video.update(title=self.title, subtitle=self.subtitle, thumbnail=str(self.thumbnail)) super(Video, self).save(*args, **kwargs) My question is, why a non required field gives me the ValueError when there is nothing to be added on the many-to-many field? And how could I fix this? -
How to port forward from Eclipse Che instance to local machine?
BACKGROUND/TANGENT INFO So after about a year of having a GoDaddy cloud service, and super disappointed with it from the get-go but what can I say I'm a loyal person. Once they announced that they would be discontinuing Cloud Server services, it was like a sign from the heavens and immediately I then created a Google Cloud account and despite still the learning curve I'm still going through ( if you've ever had a GoDaddy cloud service and used a Google cloud service... Got to admit that godaddy's cloud services way... Way Nerfed) . One of the biggest reasons I got a Cloud Server to begin with was to have an eclipse Che instance, an IDE Wherever You Are! I love it, but despite the temporary partnership between bit Nami and GoDaddy, launching a eclipse instance with them with such a mind-numbing task since the fact that there internal Factory build when launching said instance still required a ton of docker configurations... And though I can appreciate the fact that I did learn the ins-and-outs of configuring Dockers Network settings, which is not something to wince at... As soon as I got my Google Cloud account it was simply a … -
Making two player chess app with Django-- need player's board to update when opponent makes a move
So each player has their own webpage with a Javascript chessboard GUI interface, which they can click to drag pieces. When one player makes a move, I need the other player's chessboard to update with that move. I see how when one player makes a move, I can post the move to the server so that it's available for the other player to request it, but the problem is signaling the other player when a move is made, so they know when to request the new move from the server and use it to update the javascript on their page. What's a good technique to do this? -
Populating a model in Django using loops
I'm trying to make a population script that populates a model in a certain way with loops. Here is what the code might look like: models.py class ExampleModel(models.Model): name = models.CharField(max_length=32) code = models.CharField(max_length=3) description = models.TextField(max_length=128) text.txt 001 Name One Description one Description one line two 023 Name Two Description two Description two line two Description two line three AAA Name Three BBB Name Four Description three populate.py def populate(): with open("text.txt") as f: content = f.readlines() for line in content: fields = line.split(' ', 1) if len(fields[0]) == 3 and ( fields[0].strip().isupper() or fields[0].strip().isdigit() ): code = fields[0].strip() name = fields[1].strip() print("%s-%s" % (code, name)) add_object(name=name, code=code) def add_object(name, code, periship_amount): f = ExampleModel.objects.get_or_create(name=name, code=code)[0] return f if __name__ == '__main__': populate() Right now, the population script can take any line that starts with a three-character string and divide it into two making the three-character string into the code and the rest of the string into the name. What I want to do is make the entire text (the one's with description in it) below one code-name line and above the other to equal the description field of the code-name above. Does anyone know how to write that … -
django retrieve data from database using ajax and update section
I am new to django, I was trying to design a webpage where a project section will have all the projects, on the same page there will be module section and under that module section there will be commits. Now, What i want is when the user clicks on some project the module section should get updated with the modules under that project. I was able to do this much. (Here is everything you need to reference, you might need to hop into feed app there) But the problem is, I used this in my ajax to update the module section. $('#module_section').html(data); Now the index.html doesn't know about the show details button in my module section (as it is retrieved from detail.html, my detail.html has the show details button which will show the commits done under that module) and when I press the show details button in my module section, nothing happens, obviously. I need a javascript/ajax that may be able to do a query like "Select * from module where project_id = 'some_id' " (Not sure about the syntax), and then update my module section accordingly so that when someone clicks on show details of module section he will … -
Exception AttributeError: "'NoneType' object has no attribute 'path'" in <function _cb at 0x1c8e5f0> ignored
I am creating a Django command to get the json data from a url and then update the database. I get the below error message while running the command. AttributeError: "'NoneType' object has no attribute 'path'" in <function _cb at 0x1c8e5f0> ignored Code - import datetime from django.conf import settings from django.core.management.base import BaseCommand, CommandError from utils import * from app.models import Contacts import logging from appmap.settings.base import * log_path = settings.PROJECT_PATH + '/app/management/log/appmap_contacts.log' logging.basicConfig(filename=log_path, filemode='w',level=logging.INFO) import pdb; pdb.set_trace() class Command(BaseCommand): args = 'Arguments is not needed' help = 'Django admin custom command poc.' def appmap_contacts(self): api_url = <<url>> try: logger.info('Reading data from %s'%api_url) req = urllib2.Request(url) res = urllib2.urlopen(req) except Exception as e: logging.error("Exception while parsing the json data " + str(e)) return return res def handle(self, *args, **options): logger.info('Update START') cou_res = self.appmap_contacts() logger.info('Update END') Running the command - python manage.py appmap_contacts -
Fix 'column already exists' Django Migration Error?
I'm getting a "column of relation already exists" error when I try to run the Django migrate command: Operations to perform: Synchronize unmigrated apps: signin, django_rq, gis, staticfiles, admindocs, messages, pipeline, test_without_migrations, django_extensions Apply all migrations: profile, activities, contenttypes, # plus other modules... Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... DONE Applying activities.0002_auto_20170731_1939...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/srv/http/example.com/venvs/4dc40e5fc12700640a30ae0f040aa07ffc8aa1c5/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/srv/http/example.com/venvs/4dc40e5fc12700640a30ae0f040aa07ffc8aa1c5/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/srv/http/example.com/venvs/4dc40e5fc12700640a30ae0f040aa07ffc8aa1c5/local/lib/python2.7/site-packages/django/core/management/base.py", line 393, in run_from_argv self.execute(*args, **cmd_options) File "/srv/http/example.com/venvs/4dc40e5fc12700640a30ae0f040aa07ffc8aa1c5/local/lib/python2.7/site-packages/django/core/management/base.py", line 444, in execute output = self.handle(*args, **options) File "/srv/http/example.com/venvs/4dc40e5fc12700640a30ae0f040aa07ffc8aa1c5/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 222, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/srv/http/example.com/venvs/4dc40e5fc12700640a30ae0f040aa07ffc8aa1c5/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 110, in migrate self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial) File "/srv/http/example.com/venvs/4dc40e5fc12700640a30ae0f040aa07ffc8aa1c5/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 148, in apply_migration state = migration.apply(state, schema_editor) File "/srv/http/example.com/venvs/4dc40e5fc12700640a30ae0f040aa07ffc8aa1c5/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 115, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/srv/http/example.com/venvs/4dc40e5fc12700640a30ae0f040aa07ffc8aa1c5/local/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards field, File "/srv/http/example.com/venvs/4dc40e5fc12700640a30ae0f040aa07ffc8aa1c5/local/lib/python2.7/site-packages/django/contrib/gis/db/backends/postgis/schema.py", line 94, in add_field super(PostGISSchemaEditor, self).add_field(model, field) File "/srv/http/example.com/venvs/4dc40e5fc12700640a30ae0f040aa07ffc8aa1c5/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 398, in add_field self.execute(sql, params) File "/srv/http/example.com/venvs/4dc40e5fc12700640a30ae0f040aa07ffc8aa1c5/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 111, in execute cursor.execute(sql, params) File "/srv/http/example.com/venvs/4dc40e5fc12700640a30ae0f040aa07ffc8aa1c5/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/srv/http/example.com/venvs/4dc40e5fc12700640a30ae0f040aa07ffc8aa1c5/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/srv/http/example.com/venvs/4dc40e5fc12700640a30ae0f040aa07ffc8aa1c5/local/lib/python2.7/site-packages/django/db/utils.py", line … -
How to make a fancy application using Python as backend and any other language for the "fancy" part
I started coding with python around 3 months ago and build up a huge pile of codes since then. Many variables are being collected and processed. Now I think its time to make it "fancy" I would love to display the variables in a Fancy application, yet my question is, How? My code is python3. Now I want the variables to be displayed Graphically appealing. I thought about the following: Tkinter Tkinter is intregated in python so logically I tried this first. But I found Tkinter usefull for simple application, yet it was hard to make a goodlooking design. HTML I tought about setting up a website, localhost. I could combine HTML with CSS for a goodlooking site. I have no clue how to send my python variables to the site, but the internet suggest Django. (Maybe it is possible to use a website builder so I could skip a part of the code?) PHP I was reading some tutorials on diffrent languages and I realised that I could use PHP to read a textfile where python writes its values for the variables. I dont know how heavy this is for the computer. Making a goodlooking application needs to be … -
Reduce Postgresql queries in Django ManyToMany TabularAdminInline
I'm experiencing some performance issues within Django's Admin interface & Postgres. I've narrowed it down to a query that's preformed for each IngredientInline in my RecipeControl model. The more ingredients that exist within a Recipe the longer the page takes to load because is seems to want to load the queryset (Almost 2,000 records) for the IngredientInline multiple times. I'm convinced the solution is to somehow pre-cache the queryset prior to loading the page, but I'm confused at how this works and don't know what kind of problems this could cause down the road. I've looked into the difference between prefetch_related vs select_related and have tried to use both but there doesn't seem to be any change in performance when doing either. I found this question also but I'm using the admin interface, not writing my own view. So how/which admin module do I properly override to produce the desired effect? Thanks for any help. I have a model as follows: class RecipeControl(models.Model): #recipe_name choice field needs to be a query set of all records containing "FG-Finished Goods" recipe_name = models.ForeignKey(items.IngredientList, related_name='recipe_name', limit_choices_to={'category': 'FG'}) customer_recipe = models.ForeignKey(custmods.CustomerProfile, verbose_name='customer', related_name='customer_recipe') ingredients = models.ManyToManyField(items.IngredientList, through='RecipeIngredients') active_recipe = models.BooleanField(default=False) active_by = models.CharField(max_length=64, editable=False) …