Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to measure decibel value from a website?
I developed a website for conducting pure tone audiometry, which features frequencies at 500, 1000, 2000, and 4000Hz played separately in each ear. It includes a volume slider ranging from 0dB to 120dB. Users are prompted to click "next" when they can barely detect the tone, with the corresponding decibel value being saved upon clicking. My challenge lies in verifying the accuracy of the decibel values. How can I ensure that 5dB is indeed 5dB and 10dB is accurately represented? I am using Web Audio API. sample website I've heard about using an oscilloscope or spectrum analyzer for this purpose, but I wonder if there's software or a library available to assist with programming this feature. I purchased an inexpensive sound level meter and experimented with apps like Decibel X. However, accurate testing demands a soundproof environment, and the meter only detects a minimum of 30dB. Should we consider using an existing audiometer device to compare its "decibel" readings with those of our website? If so, what would be the approach? let audioContext; let oscillator; let gainNode; let isPlaying = false; let currentFrequencyIndex = 0; let frequencies = [500, 1000, 2000, 4000]; let currentEar = 'Left'; let frequencyDecibelData = []; … -
How can I stream rtsp (live video) in django app?
I tried to use StreamingHttpResponse in Django app for live rtsp streaming [https://docs.djangoproject.com/en/2.1/ref/request-response/#streaminghttpresponse-objects]. But du to documentation it's not correct. Does anyone have other solutions for this task? return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame")``` A new way to solve this problem? -
Python: Get multiple columns from database by filter
I want to get multiple columns from File table by filtering it by login_info. For example it will return 2 objects, but how can I handle it without this error get() returned more than one ParentMystudent -- it returned 2! views.py mystudent = ParentMystudent.objects.get(parent=request.session['login_info'].get('id')) query = File.objects.get(studentid=mystudent.mystudent_id) if query: for obj in query: student = Student.objects.get(registerid=obj.studentid_id) obj.student = student return render(request, 'file.html', {'query': query}) file.html {% for obj in query %} {% if obj in query.all %} <tr> <td><a href="#" class="fw-bold"></a>{{ forloop.counter }}</td> <td>{{ obj.soano }}</td> <td>{{ obj.student.lrn }}</td> <td><span src="{{ obj.file.url }}" target="_blank">{{ obj.student.lastname }}</span></td> </tr> {% endif %} {% endfor %} -
Django Switching sqlite3 to Postgres - User Unique Constraint Error
Was following this answer to switch my project database from sqlite3 to PostgreSQL, and encountered error when executing python manage.py loaddata datadump.json, my json file(google drive): django.db.utils.IntegrityError: Problem installing fixture 'C:\stuff\code\django-test01\django_project\datadump.json': Could not load auth.User(pk=1): duplicate key value violates unique constraint "users_profile_user_id_key" DETAIL: Key (user_id)=(1) already exists. I aslso tried doing python manage.py migrate --run-syncdb, python manage.py dumpdata --exclude auth.permission --exclude contenttypes --natural-foreign --natural-primary > db.json and 'TRUNCATE django_content_type CASCADE;' in dbshell, but none of above did work. Am using Django's built-in User model('User' class from 'django.contrib.auth.models'). Tried to completely erase data from database and do it again, but for no avail. Tried answers(1, 2) from related questions, but they didn't work. What can I do to fix it and migrate my data from sqlite3 to Postgres? -
Django App not Deploying Correctly on Azure Web App Service
I've been following the steps outlined in the Azure documentation to deploy my Django app on an Azure Web App Service using local git deployment. After completing the steps, I can see the code and the virtual environment with the correct packages when I SSH into the web app. However, when I visit my site, it still loads the default Azure home page instead of my Django app. I attempted to troubleshoot by running python manage.py runserver in the SSH console, but I received the following error: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). February 12, 2024 - 01:20:11 Django version 4.1, using settings 'csvvalidator.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Error: That port is already in use. It seems like the Django development server is running, but the port is already in use. I expected my Django app to be deployed following the tutorial, but it's not working as expected. Am I missing any additional steps or configurations to ensure that my Django app is properly deployed on the Azure Web App Service? Any guidance or suggestions would be greatly appreciated. Thanks! -
Is there a way to redirect a non-www subdirectory to that subdirectory with the www domain?
I'm new to web hosting and I'm currently having trouble redirecting subdirectories that don't have the www subdomain. Typing example.com/subdirectory/ just goes to https://www.example.com/ I want it to go to from example.com/subdirectory/ to https://www.example.com/subdirectory/ I'm using django, pythonanywhere, and namecheap. I've already looked a lot online but there just doesn't seem to be any examples with someone using django, pythonanywhere and namecheap. There were some cases where using htaccess solved the problem, but I don't think it's compatible with django? -
Having issues with my Django form ; returning invalid
I keep getting form.is_valid return false from my Django form Here is my views.py def book_bus(request): if request.method == 'POST' : form = bookbusform(request.POST) if form.is_valid() : cd = form.cleaned_data current_loc = cd['current_location'] destination = cd['Destination'] departure = cd['departure_date'] User = get_user_model() if 'booknow' in request.POST : user = User.objects.get(phone_number=request.user.phone_numbe> booking = Booking.objects.create(current_Location = current_l> booking.created_by = user booking.save() return redirect('payonline') else : user = User.objects.get(phone_number=request.user.phone_numbe> booking = Booking.objects.create(current_Location = current_l booking.created_by = user booking.save() return redirect('home') else : return redirect('error-page') else : form = bookbusform() context = { 'form' : form } return render(request,'bookbus.html',context) My forms.py file class bookbusform(forms.Form) : current_location = forms.ChoiceField(choices = Bus_Terminal.objects.values_list("id","name"),widget = forms.Select(attrs={"class":"selec> Destination = forms.ChoiceField(choices = Bus_Terminal.objects.none(),widget = forms.Select(attrs={"class":"select","id":"Des"})) departure_date = forms.DateField(widget = forms.DateInput(attrs={"type":"date","min":min_date,"max":max_date})) -
Django Updateview in modal
im not so confirm in Django, and Im trying to change some parts from a existung project to my wishes. The existing project is not from me, I downloaded from Github here: https://github.com/AliBigdeli/Django-Smart-RFID-Access-Control/ I added in Card management one new field in models.py class UIDCard(models.Model): ... ammount = models.DecimalField(max_digits=8, decimal_places=2, default=0) ... Also added in the folder dashboard/api/serializers.py the price in class CardReaderSerializer Now I changed some parts in templates/card-management.html Added the field "ammount" in the genral overview, is showing me the Database value Added a Pay button, open a new Modal window, the plan is to add some money on it. The enterred value is saving on the Database, but with two issues. first, I cant see the existing values from the Database in the formfields prefilled. Like in the edit part second, the Update button is saving the value but the modal window is not closing I cant find the problems in the code, can somewhre helping me please The complete changed .html file: {% extends 'dashboard/base.html'%} {% block content %} <div class="d-flex"> <div> <h1 class="mt-4">Cards</h1> </div> <div class="ms-auto mt-4"> <button type="button " class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#CreateFormModal" id="CreateDevice"> Add Card ID </button> </div> </div> <hr> <div class="table-responsive" style="height: … -
Papertrail logs not displaying for Django app in production
I have a Django app that is deployed to production using Heroku. I am currently trying to integrate papertrail logging but no logs are being sent to production. At this point I am at a total loss as to why my logs are not going through. I am not using papertrail as a Heroku addon, but am using the web interface. This is what my LOGGING setting is in settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, 'papertrail': { 'level': 'INFO', 'class': 'logging.handlers.SysLogHandler', 'address': ('logsX.papertrailapp.com', XXXXX), 'formatter': 'verbose', }, }, 'loggers': { '': { # This is the root logger, capturing logs from any logger. 'handlers': ['console', 'papertrail'], # Start with 'console' for development. Add 'papertrail' for production. 'level': 'DEBUG', 'propagate': True, }, }, } NOTE: In my code the address is correct, I am of course redacting it in this post. In my views.py I have the following code: import logging logger = logging.getLogger(__name__) def index(request): logger.warning('test') I have deployed this to production but I see no logs coming in. I am at a loss … -
How to display data from api json for django
I'm trying to create a weather website in django but I don't know exactly how to get apis data and display it in my templates. following a tutorial I arrived at this view: from django.http import HttpResponse import requests def weatherdata(request): response = requests.get('https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&hourly=temperature_2m,relative_humidity_2m,precipitation').json() context = {'response':response} return render(request,'home.html',context) and this html: <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <strong>LATITUDE AND LONGITUDE</strong> {{latitude}} {{longitude}} </body> </html> considering the following lines in the api: {"latitude":52.52,"longitude":13.419998, and the result was, basically nothing. No error but no information was printed in the screen how do I solve this? -
How to save logs, to S3Boto3Storage, with Django Logging
I need to save my logs to a file on dedicated storage (using S3BotoStorage). I haven't found any working solution yet. Does anyone know how to make it work? I need to incorporate something similar to logging.handlers.RotatingFileHandler with backups. This is my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s %(levelname)s %(name)s %(message)s' }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'standard', 'filters': [], }, 'file': { 'level': 'INFO', 'class': 'fundamental.cdn.backends.LogsRootS3BotoStorage', 'formatter': 'standard', 'filename': 'logs.log', }, }, 'loggers': { logger_name: { 'level': 'INFO', 'propagate': True, 'handlers': [],#['file'], } for logger_name in ('django', 'django.request', 'django.db.backends', 'django.template', 'articles') }, 'root': { 'level': 'DEBUG', 'handlers': ['console'], } } this is cdn.backed from storages.backends.s3boto3 import S3Boto3Storage ... class LogsRootS3BotoStorage(S3Boto3Storage): location = "logs" file_overwrite = False -
How do i use external file storage for user uploaded files in Django
I have deployed my django application on vercel and the mysql database is deployed on Clever Cloud. I have used the Clever Cloud File Storage (FS Bucket) service, free tier to store user uploaded files and images but I am not able to make it work I get the error: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Here is my configuration DEFAULT_FILE_STORAGE = 'storages.backends.sftpstorage.SFTPStorage' SFTP_STORAGE_USE_AGENT = False # Avoid using insecure key agent authentication SFTP_STORAGE_HOST = 'bucket-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxx-fsbucket.services.clever-cloud.com' SFTP_STORAGE_USERNAME = 'username@bucket_name' # Use correct IAM user with access # Retrieve password securely from environment variable (highly recommended) SFTP_STORAGE_PASSWORD = 'xxxxxxxxxxxx' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = 'https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-fsbucket.services.clever-cloud.com/portfolio/' I cant seem to find the issue. I am open to use any other file storage if it's free -
Encountering Server Error (500) During Website Deployment Without Clear Error Messages On Render.com
During deployment on Render.com, I encounter a Server Error (500) without receiving any warnings or errors in the logs. Interestingly, only pages that don't interact with the database load successfully, suggesting potential issues with database permissions or connection configurations. Unfortunately, the lack of detailed error messages makes it challenging to pinpoint the exact cause of the problem. Seeking insights and solutions to resolve this deployment issue. from pathlib import Path import os import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY', default='your secret key') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = 'RENDER' not in os.environ ALLOWED_HOSTS = [] RENDER_EXTERNAL_HOSTNAME = os.environ.get('RENDER_EXTERNAL_HOSTNAME') if RENDER_EXTERNAL_HOSTNAME: ALLOWED_HOSTS.append(RENDER_EXTERNAL_HOSTNAME) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'catalogoApp', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'panelBM.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'panelBM.wsgi.application' # Database # https://docs.djangoproject.com/en/5.0/ref/settings/#databases … -
how to show image in html
#models.py class Contact(models.Model): name = models.CharField(max_length=50, null=False, blank=False, unique=False) photo = models.ImageField(upload_to='static/photos/', null=True, blank=True) def __str__(self) -> str: return f'{self.name} {self.photo}' #forms.py class ContactForm(forms.Form): name = forms.CharField(required=True, label='Name') photo = forms.ImageField(required=False, label='Photo') #views.py def post(self, request:HttpRequest)->HttpResponse: # print(request.POST) form = ContactForm(request.POST, request.FILES) if form.is_valid(): Contact.objects.create(name=form.cleaned_data['name'], photo=form.cleaned_data['photo']).save() #. . . class ContactDetail(DetailView): model = Contact #contact_detail.html <ol> <b>{{object.name}}</b><br> Photo: <img src="{{object.photo}}" width="55%"> </ol> I've this but when I want t see that contact, there's no image in page. what I should do? it just shows this atajan(name) -
Troubleshooting Plesk: Resolving Python Django App Issues
I recently encountered a frustrating issue while attempting to deploy my Python Django 3 application on a hosting server running Plesk on CentOS. Every time I tried to access the application URL, I was greeted with a discouraging 403 error. Despite my efforts to tweak various Apache, nginx, and HTTPS directives within Plesk, as well as experimenting with Passenger, none of my attempts seemed to resolve the issue. Has anyone else faced a similar challenge, and if so, how did you manage to overcome it? I'm eager to hear any suggestions or insights that could help me get my Django app up and running smoothly. Thanks in advance for any assistance! -
Django migration error for custom model where if tried it make migraiton shows table doesn't exist
I have created login register app for that I have used django django.contrib.auth.models import abstractuser and used inbuilt user model and added more fields into it and then in setting.py add this line "AUTH_USER_MODEL = 'login_register.loginRegister'" and when tried to make migrations it shows error that login_register doesn't exist, I undestood that it is trying to refernce it before it's initialization but i don't understand I am just trying to makemigrations and not call it. Tried to makemigrations and migrate into database but getting error table doesn't exist -
Dump Web Client Sending the same post request MANY times to Django server
I am developing an acquisition server for an IoT application, I am using Django web framework for this task. (Acquisition server is a server that recieves messages from a client "a hardware Microcontroller in my case" and saves the data it recieves to the database) The client I am working with is a closed source controller, so I cannot modify how it behaves. I only have control over my acquisition server. The problem: The controller is sending the same request with the same data multiple times in a row and django is opening a new thread for every request. I want Django to handle the request of the controller and not open a new thread for the controller (the controller is dump), after Django handles the request it sends a confirmation messages to the controller and the controller would send next request. How can I achieve that in Django? I do not know where to start or how to look for an answer for my question. -
how to combine models in a view?
I have two models, submission and additionalinfo. class Submissions(models.Model): STATUS=() CAUSE=() def create_new_ref_number(): return str(random.randint(1000000000, 9999999999)) submissions_number_id = models.CharField(max_length=10,blank=True, unique=True, default=create_new_ref_number,editable=False) client = models.ForeignKey(ProfileUser, on_delete=models.CASCADE, related_name='submissions') contents = models.TextField() status = models.CharField( max_length=30, choices=STATUS, default='1') submissions_supervisor = models.ForeignKey(User,on_delete=models.SET_NULL, null=True, related_name='submissions_supervisor') contractors = models.ManyToManyField(User, related_name='contractors') submissions_cause=models.CharField(max_length=30, choices=CAUSE, default='3') execution_date = models.DateField(null=True, blank=True) details_planned_service=models.TextField(null=True) created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True, null=True) class AdditionalInfo(models.Model): submission = models.ForeignKey(Submissions, on_delete=models.CASCADE, related_name='additional_info', default='') contents = models.TextField() submissions_supervisor = models.ForeignKey(User,on_delete=models.SET_NULL, null=True, related_name='additional_info_supervisor') created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True, null=True) The website displays all submissions according to the date they were scheduled, and it is also possible to click the mini preview which opens the MODAL WINDOW, and here is the problem because the data from the submission model is all displayed, but I don't know how to add additional information to it. def Schedule(request): report=Submissions.objects.filter(status=4) staff = User.objects.filter(groups__name='Realization') list=[0,1,2,3,4,5,6,7,8,9,10,11,12,13] dt=[] for l in list: date=datetime.date.today() next_date = date + timedelta(days=l) dt.append(next_date) schedule_dict=dict() schedules=Submissions.objects.all() for schedule in schedules: schedule_dict[schedule] = schedule.contractors.all() context={ 'report':report, 'next_data':dt, 'staff':staff, 'schedules':schedules, } return render(request, 'staff/work_schedule.html', context) {% for d in next_data %} <table class="table table-striped table-hover"> <div style="width: 100%;background-color: rgb(0, 0, 0);"><span style="color: white;font-weight: 800;font-size: 14px;">{{d|date:'l'}}</span> <span style="color: rgb(178, 220, 7);font-weight: … -
expected str, bytes or os.PathLike object, not tuple how to solv
say me fast Hello sir this is my error ohter django same project good working then all copy and paste this code other project then show this error this error two days but not solving here are many django developer you have idea and say me where is error which models or views or admin TypeError at /admin/post/post/add/ expected str, bytes or os.PathLike object, not tuple enter image description here -
is there any one having solutions to reverse and redirect to pages in Django after submitting the form or update
I redirect to goals list by clicking the category ID and I want to add an other goal and then redirect to goals list but display errors NoReverseMatch at /planningCycle/goal_update/15/ Reverse for 'planning' with no arguments not found. 1 pattern(s) tried: ['planningCycle/planning/(?P<id>[0-9]+)/\\Z'] enter image description here my views.py enter image description here my urls.py enter image description here my html -
Connect flutter app to django using websockets
I'm completely new to WebSockets, so basically I'm trying my best to create in my Django project and integrate it in my Flutter project. The idea is to have a rooms and the participants of those rooms to be able to chat. So, in my Django settings, I have added 'daphne' in the installed apps, I have created my chat consumers like so: class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): # scope is the request parameters passed from the url route self.room_id = self.scope['url_route']['kwargs']['room_id'] self.room_group_name = 'chat_%s' % self.room_id # Join room group await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() async def disconnect(self, close_code): # Leave room await self.channel_layer.group_discard(self.room_group_name, self.channel_name) That is how my room and Message models look: class Message(models.Model): """Chat message model""" body = models.TextField() sent_by = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) class Meta: ordering = ('created_at',) def __str__(self): return f'{self.sent_by}' class Room(models.Model): class Meta: verbose_name_plural = "Rooms" unique_id = models.CharField( max_length=8, primary_key=True, editable=False, unique=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=101, null=True, blank=True) password = models.CharField(max_length=50, blank=True, null=True) users = models.ManyToManyField(User, through='UserRoom', related_name='users_room') messages = models.ManyToManyField(Message, blank=True) def __str__(self) -> str: return str(self.name) I have added the consumers to my urls: path('ws/<str:room_id>', chat_consumers.ChatConsumer.as_asgi()), And configured my … -
How can I save my photo that is taken from form ImageField in database
#models.py class Contact(models.Model): name = models.CharField(max_length=50, null=False, blank=False, unique=False) photo = models.ImageField(upload_to='static/photos/', null=True, blank=True) def __str__(self) -> str: return f'{self.photo}, {self.name}' #admin.py @admin.register(Contact) class ContactAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'photo'] #forms.py class ContactForm(forms.Form): name = forms.CharField(required=True, label='Name') photo = forms.ImageField(required=False, label='Photo') #views.py def post(self, request:HttpRequest)->HttpResponse: form = ContactForm(request.POST) if form.is_valid(): Contact.objects.create(name=form.cleaned_data['name'], photo=form.cleaned_data['photo']).save() And then when I've created contact with that photo, there's name but no src of photo in admin panel. It seems like it haven't been saved. What could be the problem of that..? -
Pagination not working with django-tables2
I don't get any pagination at all, it is supposed to be automatic. I am using django_mail_admin for the models Table code class IncomingTable(tables.Table): class Meta: model = IncomingEmail template_name = "django_tables2/bootstrap.html" fields = ("id", "subject",) View code, there seems to be some duplication of models class IncomingMail(SingleTableView): table_class = IncomingTable queryset = IncomingEmail.objects.all().order_by("-id") template_name = "incoming.html" Any help would be great, thanks. -
List of all values in Django model attribute
I am creating an e-commerce website and I want to allow the user to filter the search results by various products specs. I want to return in my API a meta dictionary containing all the values each product attribute has. For example, if the user searches for 'iPhone', the response should look like this: { 'data': { ... }, 'meta':{ 'options':{ 'model': ['iPhone 12', 'iPhone 13', 'iPhone 14'], 'manufacturer': ['Apple'], ... } } } Here is my model for reference: class Product(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, null=False, blank=False) description = models.TextField(max_length=2048, null=False, blank=True) price = models.FloatField(null=False, blank=False, default=0) model = models.CharField(max_length=255, null=False) manufacturer = models.CharField(max_length=255, null=False) seller = models.CharField(max_length=255, null=False) So far i have tried using this, where products is my QuerySet of Product entities after applying the 'iPhone' search: products.values_list('model') The problem with this is that it returns a QuerySet, but I want a list. I was hoping there is a one-liner that I don't know about. -
In Django Admin, how do I reference reverse foreign key relations for `list_display`?
In my app, we may have new languages or dialects of languages appear at any time, and text written in one language or dialect may need to be translated into another. That's why we handle text by relating text in different languages into "families" (i.e. the translation set into different languages). class StringFamily(models.Model): id = models.AutoField(primary_key=True) # plus some other fields class String(models.Model): id = models.AutoField(primary_key=True) # the reference to StringFamily family = models.ForeignKey(StringFamily, null=False, on_delete=models.CASCADE) # other important stuff language = models.ForeignKey(Language, on_delete=models.DO_NOTHING) dialect = models.ForeignKey(Dialect, null=True, on_delete=models.SET_NULL) text = models.TextField(null=False) Unfortunately this complicates using the Django ORM. When we hit a problem with the app, we're generally saved by using raw SQL to deal with this setup. But I also want to use the Django admin, and I don't see any SQL workaround there. In particular, there are all sorts of models that have some text that may appear in multiple languages, like so: class Element(models.Model): id = models.AutoField(primary_key=True) element_role = models.ForeignKey(ElementRole, null=False, on_delete=models.RESTRICT) string_family = models.ForeignKey(StringFamily, null=True, on_delete=models.SET_NULL) # plus more fields What I want is to be able to something like this (everything here works except "display_english_string"): class ElementAdmin(admin.ModelAdmin): list_display = ("element_role", "display_element_type", "display_english_string") This works …