Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using mock to create a 'request' attribute for testing a class method in Django
I am new to testing and need help testing a method in Django. I have tried using Client() and RequestFactory(), but because of the method's reliance on other methods, I feel that it is easier to test the method in isolation. Here is the test: class EmailVerificationViewTest(TestCase): def setUp(self): User = get_user_model() self.view = EmailVerificationCode() self.view.time_diff = Mock(return_value=False) self.view.user_code = '0000000000' self.view.code = '0000000000' def test_library(self): self.view.check_code() The problem is that I keep getting an error whenever self.request is called: user_record = User.objects.get(pk=self.request.user.pk) AttributeError: 'EmailVerificationCode' object has no attribute 'request' OR (depending whether time_diff is set to True or False) messages.info(self.request, AttributeError: 'EmailVerificationCode' object has no attribute 'request' The class and method to be tested: (login is required through the OTPRequiredMixin) class EmailVerificationCode(OTPRequiredMixin, FormView): def check_code(self): try: if self.time_diff(): if str(self.user_code) == str(self.code): user_record = User.objects.get(pk=self.request.user.pk) user_record.is_user_verified = True user_record.save() messages.success(self.request, _('Your email has been verified - thank you' )) return redirect(reverse('account:user_profile')) else: messages.error(self.request, mark_safe(_( 'Sorry, but your code did not match.' ))) return redirect(reverse('account:verify_email_code')) else: messages.info(self.request, mark_safe(_('Sorry, but your code has expired.<br>' ))) return redirect(reverse('account:verify_email')) except (AttributeError, ObjectDoesNotExist): messages.warning(self.request, mark_safe(_('We are very sorry, but something went wrong. 'Please try to login again' ))) return redirect(reverse('two_factor:login')) My question is, how … -
Request.get blocked coming from Atom only
I am writing a django app with communcitaion to external python scripts in other software. As I am currently checking all basi requirements and their functionality, I am working with the standard django sql lite testserver. While testing, I am facing a weird firewall/ site blocking issue. A simple request.get() is working fine from windows cmd, receiving my json response. Opening the page in any browser from any computer within my company network works as well. However, when simply launching the request from atom on the local host pc, it fails with 403 - response.content.decode() showing the site is receiving a prompt due to being uncategorized and I would have to click to "continue browsing for work related purposes". As this is only happening from within atom - any ideas how to prevent this? What I tried so far: Adding headers (not change) launching a subprocess calling cmd with the command (works, but sort of failing the purpose of the script) Goal is to simply retrieve a json response from a view so I can transfer the information to my program. Thanks a lot Thomas -
create auto increment integer field in django
i want to create auto increment integer field. I want to create an ID for each user. I am a beginner and please explain completely and clearly :) I want to automatically assign an ID to each user. my Model: from django.db import models class User_account(models.Model): email = models.EmailField() fullname = models.CharField(max_length=30) username = models.CharField(max_length=20) password = models.CharField(max_length=30) marital_status = models.BooleanField(default=False) bio = models.CharField(default='' ,max_length=200) def __str__(self): return f"(@{self.username}) {self.fullname}" def save(self, *args, **kwargs): self.username = self.username.lower() self.email = self.email.lower() return super(User_account, self).save(*args, **kwargs) my View: from django.shortcuts import render from .models import User_account def profile(request, username): users = User_account.objects.all() for user in users: if username == user.username: return render(request, 'account_app/profile.html', context={"user_info":user}) def users_list(request): users = User_account.objects.all() return render(request, 'account_app/users_list.html', context={"user_info":users}) -
Not able to load images from static folder in django
I a not able to load image from static dir in Django. Below is the picture of my file structure. In settings.py S STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR,'static') When I try to load the image file from STATIC_URL, it is producing this error: it is just not loading images but the text from my home-view.html is loading file thus django is not able to locate the image files. Could you please advise why are images not loading? My complete settings.py file : """ Django settings for myproject project. Generated by 'django-admin startproject' using Django 4.0.4. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent print("Path is : ", os.path.join(BASE_DIR, 'myproject/template')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-(ep(j)h+$(zro2!9r3bm0fj^!84-1c9d+)$be4hgrq4_#6d^r-' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myproject' ] MIDDLEWARE … -
How to get a relation from a relation in a serializer?
I have 3 models: class Artist(Timestamps): name = models.CharField('Name', max_length=255, blank=True) ... class Festival(Timestamps): name = models.CharField(max_length=255, blank=True) ... class Event(Timestamps): artist = models.ForeignKey(Artist, on_delete=models.CASCADE, null=True) festival = models.ForeignKey(Festival, on_delete=models.CASCADE, null=True) Now I wan't all the id's from the festivals an artist is playing. I have a serializer like this: class ArtistFestivalSerializer(serializers.ModelSerializer): class Meta: model = Artist fields = ('id', 'name', 'event_set') But this only gives me the id's of the event. Any ideas how to get trough the Event to the Festival? Thanks in advance -
Django : Inheritance error- TemplateSyntaxError at / “Could not pass the remainder”
I have a website running using Django that uses the following dgango blocktag to render text within a base.html file. {% block content %} <h1>Welcome </h1> <p1> This is the site template </p1> {% endblock content %} However, to describe a page content and not the site itself, I have the following page.html which is meant to inherit the code from base.html {% extends “base.html” %} {% block content %} <h1>Greetings</h1> <p>The_page_template</p> {% endblock content %} Changing views.py from render base.html to render page.html as follows causes the error. from django.shortcuts import render def index(request): #return render(request, "base.html") // this works return render(request, 'pages/page.html') // this does not The uploaded image is a screenshot of the broken webpage. The best explanation I can offer is that there is an error in the spacing of the code or the pathing to page.html. With pathing I do notice the broken webpage does point to page.html. The following is a relevant statement from settings.py ‘DIRS’: [BASE_DIR / ‘site/templates’] 'APP_DIRS' : TRUE For the sake of completeness, the following paths are described. root/site/templates/base.html root/pages/templates/pages/page.html root/pages/views.py root/site/settings.py Any help appreciated in resolving this error - thanks -
I am new to Django and I can't understand a few errors related to os.environ.setdefault
I found a GitHub repo for reference and practice but when I'm trying to run it on my system it is giving me this error: Traceback (most recent call last): File "C:\Users\Nikita\Desktop\GitHub files\HomieChat-main\homiechat\manage.py", line 22, in main() File "C:\Users\Nikita\Desktop\GitHub files\HomieChat-main\homiechat\manage.py", line 9, in main os.environ.setdefault('DJANGO_SETTINGS_MODULE', config('LOCAL_SETTINGS_MODULE')) File "C:\Users\Nikita\Desktop\GitHub files\HomieChat-main\env\lib\site-packages\decouple.py", line 199, in call return self.config(*args, **kwargs) File "C:\Users\Nikita\Desktop\GitHub files\HomieChat-main\env\lib\site-packages\decouple.py", line 83, in call return self.get(*args, **kwargs) File "C:\Users\Nikita\Desktop\GitHub files\HomieChat-main\env\lib\site-packages\decouple.py", line 68, in get raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) decouple.UndefinedValueError: LOCAL_SETTINGS_MODULE not found. Declare it as envvar or define a default value. I can't understand what this error means. I installed the requirements.txt but it's the same. On searching the project for LOCAL_SETTINGS_MODULE, I found: os.environ.setdefault('DJANGO_SETTINGS_MODULE', config('LOCAL_SETTINGS_MODULE')) in settings.py, asgi.py, and wsgi.py. I need to understand what this LOCAL_SETTINGS_MODULE is and how to fix this error. -
NGINX slow static file serving
I have a web service served by nginx. I'm using protected routes and nginx X-Accel header from my web server. However these files served slowly compared to other services on the same server. For example downloading media files is around 1MB/s. Server usual upload link is around 400-500Mbps. This is the relevant nginx configuration: server { listen 80; # Set correct charset charset utf-8; sendfile on; sendfile_max_chunk 0; proxy_max_temp_file_size 0; tcp_nopush on; tcp_nodelay on; keepalive_timeout 5; types_hash_max_size 2048; server_tokens off; client_body_buffer_size 1k; client_header_buffer_size 1k; client_max_body_size 4M; large_client_header_buffers 2 1k; client_body_timeout 10; client_header_timeout 10; send_timeout 10; location /protected/media/ { internal; alias /media/; try_files $uri $uri/ =404; } } This nginx instance is running in Docker, files are mapped as volumes for this container. Eg.: the /media/ folder is mapped as a volume from host. The host folder is a local folder, so it is not a mounted network folder. -
TypeError: super(type, obj): obj must be an instance or subtype of type in Django
I have two forms-- userthesisForm and thesisForm-- that have the same model to save on. Basically, the thesisform is for the Admin and the userthesisForm is for the student (normal user). I do not encounter any problem with the Admin saving the thesisForm, but i do get this error TypeError: super(type, obj): obj must be an instance or subtype of type in my def submit_thesis for student submitting the userthesisForm. How do I resolve it? Thanks in advance This my code for saving the thesisForm in views.py: def add(request): if request.method == "POST": form = thesisForm(request.POST, request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.uploader = request.user; obj.save() messages.success(request, "Project created successfully!" ) return redirect('/manage') else: form = thesisForm() return render(request,'Add.html',{'form':form}, ) This is for saving the userthesisForm: def submit_thesis(request): if request.user.is_superuser: return redirect('/manage') else: if request.method == "POST": form = thesisForm(request.POST, request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.uploader = request.user; obj.status = 'Pending'; obj.save() messages.success(request, "Project submitted successfully!" ) return redirect('/myrepository') else: form = thesisForm() return render(request,'submit_thesis.html',{'form':form}, ) And the userthesisForm the student will fill up class userthesisForm(forms.ModelForm): class Meta: model = thesisDB fields = ('title', 'author', 'published_date','tags','short_description', 'pdf', 'image_banner', 'status') readonly_fields = ['course', 'shell_location', 'date_created'] widgets = { 'title': forms.TextInput(attrs= … -
another -> django.db.utils.OperationalError: (1709, 'Index column size too large. The maximum column size is 767 bytes')
I have the following problem, but first my development environment: ubuntu 18.04 python 3.7.4 mariadb 10.7.4 django 3.2.13 Attempt to configure django-allauth 0.50.0 I follow the steps of the official website and everything is ok, but, when it comes time for python manage.py makemigrations all right, but when I give python manage.py migrate I got this error: django.db.utils.OperationalError: (1709, 'Index column size too large. The maximum column size is 767 bytes') I already try all kinds of solutions that I found here, Like This , but all relate about mariadb 10.1 and 10.2, where it is assumed that in this last version the problem should be solved, but here I have it. pd: excuse my english -
data from database is not showing in html template in django
I fetched data from books table in views.py and passed to show.html as dictionary.It is not showing.also i wanted to check if there is key passed in html..so purposely wrote paragraph after {%if key1 %} ,it is not showing that paragraph also.what will be the reason or my fault? here is my code snippet views.py def show(request): books = Books.objects.all() return render(request,'app/show.html',{'key1':books}) urls.py from django.urls import path from . import views urlpatterns = [path("",views.index,name = 'home'), path('show/',views.show,name= 'show'), ] models.py class Books(models.Model): book_num = models.IntegerField() auth_name = models.CharField(max_length = 50) book_name = models.CharField(max_length = 100) def __str__(self): return self.auth_name show.html <center> <table> <tbody> <th>Available books</th> {%if key1%} <P>please check if issued</p> {% for i in key1 %} <tr> <td>Author name:{{i.auth_name}}</td> <td>Book title:{{i.book_name}}</td> </tr> {% endfor %} {% endif %} </tbody> </table> </center> -
django login / register auth safe?
I knew that django already has the auth system . However, I heard that either session and token are needed for security. should I build login, logout, registeration with session or token in view? or is it included in django's auth? -
How can I fix my code For Django's reply comment
When entering a reply comment, It will be redirected to my post with comments How can I fix it? Please Someone help me post_detail.html <!-- Reply Button Area --> <button class="btn btn-sm btn-secondary" type="button" style="float:right" data-toggle="collapse" data-target="#replyBox{{comment.id}}" aria-expanded="false" aria-controls="replyBox{{comment.id}}"> Reply </button> <div class="collapse" id="replyBox{{comment.id}}"> <div class="card card-body my-2"> <form action="/blog/{{ comment.pk }}/reply_comment/" method="post"> {% csrf_token %} <div class="form-group"> <label for="comment">Reply </label> <input type="text" class="form-control" name="comment" placeholder="type the comment"> <input type="hidden" name="parentSno" value="{{comment.id}}"> </div> <input type="hidden" name="post.pk" value="{{post.pk}}"> <button type="submit" class="btn btn-sm btn-primary">Complete</button> </form> </div> </div> <!-- Reply Button Area END --> Views.py def reply_comment(request , comment_pk) : if request.user.is_authenticated : comment = get_object_or_404(Comment , pk=comment_pk) if request.method == 'POST' : recomment_form = ReCommentForm(request.POST) if recomment_form.is_valid() : recomment = recomment_form.save(commit=False) recomment.author = request.user recomment.comment = comment recomment.save() return redirect(comment.get_absolute_url()) return redirect(comment.post.get_absolute_url()) else : raise PermissionError -
django model data returns none in html but shows in admin panel
ive created a model that lets users create a simple post however when the data is submitted it registers in the admin panel but will not display in the html. I can edit in admin and the images even up in the folder unfortunately I cannot find out what the issue is models.py from distutils.command.upload import upload from django.db import models from django.forms import CharField, ImageField from django.forms.fields import DateTimeField from matplotlib import image from sqlalchemy import true from django.contrib import admin # Create your models here. class Posts(models.Model): image = models.ImageField(upload_to='images/') quote = models.TextField(null=True) date = models.DateTimeField(auto_now_add=True, null=True) views.py from django.contrib.auth import login, authenticate from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect from requests import request from users.forms import SignUpForm from matplotlib.style import context from django.http import HttpRequest, HttpResponse from .models import Posts def signup(request): if request.method == 'POST': form = SignUpForm(request.POST)# was UserCreationForm if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('profile') #profile else: form = SignUpForm() #was UserCreationForm return render(request, 'signup.html', {'form': form}) def posts(request): userpost = Posts.objects.all() return render(request, 'posts.html', {'userpost': Posts} ) urls.py from django.urls import path from … -
Join django tables
I need to connect the Alumno table with the Horario, how could I do the syntax? I need to get the id_curso of each Alumno, and with that id_curso join it to the Horario table but I don't know how to do it I think you have to use select_related or prefetch_related, which I don't know very well how to use, I tried to create a variable to get the id_course and with that variable use filter but I didn't take it Helpme please models.py class Alumno(models.Model): rut_alumno = models.IntegerField(primary_key=True) dv_alumno = models.CharField(max_length=1) p_nombre = models.CharField(max_length=15) s_nombre = models.CharField(max_length=15, blank=True, null=True) ap_paterno = models.CharField(max_length=15) ap_materno = models.CharField(max_length=15, blank=True, null=True) fecha_nac = models.DateField() genero = models.CharField(max_length=1) direccion = models.CharField(max_length=25, blank=True, null=True) nivel_socio = models.CharField(max_length=10) id_examenes = models.OneToOneField('ExamenCono', models.DO_NOTHING, db_column='id_examenes') rut_apoderado = models.ForeignKey('Apoderado', models.DO_NOTHING, db_column='rut_apoderado') id_colegio = models.ForeignKey('Colegio', models.DO_NOTHING, db_column='id_colegio') id_curso = models.ForeignKey('Curso', models.DO_NOTHING, db_column='id_curso') id_comuna = models.ForeignKey('Comuna', models.DO_NOTHING, db_column='id_comuna') class Meta: managed = True db_table = 'alumno' class Curso(models.Model): id_curso = models.IntegerField(primary_key=True) grado = models.CharField(max_length=1) educacion = models.CharField(max_length=10) letra = models.CharField(max_length=1) id_colegio = models.ForeignKey(Colegio, models.DO_NOTHING, db_column='id_colegio') rut_profesor = models.OneToOneField('Profesor', models.DO_NOTHING, db_column='rut_profesor') class Meta: managed = True db_table = 'curso' class Horario(models.Model): id_horario = models.IntegerField(primary_key=True) dia = models.CharField(max_length=10) hora_inicio = models.CharField(max_length=5) hora_termino … -
insert ₹ in python Django mysql. i'm using frontend react and backend Python
Hi There when i was entering ₹ in a textfield i'm getting django.db.utils.OperationalError: (1366, "Incorrect string value: '\\xE2\\x82\\xB9' for column 'sk_ver_reason' at row 1") this textfield is a description box, mysql acception other countries curreny sign but not in indian currency, i have chages much collation from utf8mb... when i hit api this sign failed, but the entry for this api enter in db, same i hit again it run succefully, is it python django error or purely mysql db error. in below image you can see collation of that perticualr field. -
ApplicationOAuth using PyGithub in Django
I am building Github App. I have tried to access repository from Github by using Access tokens, It will work fine Here is the Code username = "user" reponame = "test" g = Github("my_access_token") repo = g.get_repo(username + "/" + reponame) files = repo.get_contents("") But now I want to access the repository by using Application authorizing, for this I am using PyGithub library. Here is the link which demonstrate what i am trying to do exactly. (Must read this..Please) and This is the PyGitHub Docs to achieve above functionality. I am not Getting how to implement this exactly. -
Batch Complete Tasks in DRF
I have my Django website where i can have tasks created and subtasks under tasks i have mark complete option which is working fine i need them to be completed in batch like selecting multiple tasks at once and complete them. serializers.py: class TaskCompleteSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ( 'is_done', ) def update(self, instance, validated_data): person = self.context['request'].user.person task_is_done = validated_data.get('is_done', False) if task_is_done: instance.subtasks.update(is_done=True) instance.is_done = task_is_done instance.done_by.set([person]) instance.save() return instance models.py: class TaskUpdateAPIView(UpdateAPIView): permission_classes = " " serializer_class = TaskCompleteSerializer queryset = Task.objects.all() model = Task lookup_url_kwarg = 'task_id' -
Missing data from template to view
I created a form and am trying to retrieve the data from the view so I can send it to an email. Once I render the page I get a 'keyerror'. I printed the values I am getting from the form and noticed I am not getting the 'phone_number' input. I'm trying to figure where is going the phone_number input Here's my code {% extends "base.html"%} {% load static %} {% block contenido %} <!-- Contact Section--> <section class="page-section" id="contact"> <div class="container"> <!-- Contact Section Heading--> <h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Contact Me</h2> <!-- Icon Divider--> <div class="divider-custom"> <div class="divider-custom-line"></div> <div class="divider-custom-icon"><i class="fas fa-star"></i></div> <div class="divider-custom-line"></div> </div> <!-- Contact Section Form--> <div class="row justify-content-center"> <div class="col-lg-8 col-xl-7"> <!-- * * * * * * * * * * * * * * *--> <!-- * * SB Forms Contact Form * *--> <!-- * * * * * * * * * * * * * * *--> <!-- This form is pre-integrated with SB Forms.--> <!-- To make this form functional, sign up at--> <!-- https://startbootstrap.com/solution/contact-forms--> <!-- to get an API token!--> <form id="contactForm" method="post"> {% csrf_token %} <!-- Name input--> <div class="form-floating mb-3"> <input name="full_name" class="form-control" id="full_name" type="text" … -
copy some column from a table to another table
guys I have made two models in Django. first model contains- id (primary key) name age address gender second model contains- id (primary key) name age college class What I am trying to achieve is every time I make entry in first model table it automatically copies name and age field from first model table to second model table. I have tried Foreignkey, OnetoOneField, but could not succeed. I am using Sqlite. -
How to run _icontains method on a foreignkey field in django
I am building a dummy E-commerce site. For this, I wish to build a staff portal where I can search for pending orders by a user's first name. I have made a foreignkey field on my model that I am referencing. But when I use the __icontains method in my views on user field, I get Related Field got invalid lookup: icontains error. I wish to return all orders that have been made by a user that have a certain searched string in their first name. My views.py: class delivery_staff_search_pending_orders(LoginRequiredMixin, generic.View): def get(self, *args, **kwargs): if self.request.user.groups.filter(name='Delivery_staff_admin').exists(): search_query = self.request.GET['query'] filter_form = PendingOrdersFilterForm() orders = Order.objects.filter(preproccessed=True, ordered=True, delivered=False) searched_pending_orders = orders.filter(user__icontains=search_query) context = { "filter_form": filter_form, "pending_orders_list": searched_pending_orders } return render(self.request, "staff/delivery/pending_orders.html", context) My Order model: user = models.ForeignKey(User, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) ref_code = models.CharField(max_length=20, default=1234) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) billing_address = models.ForeignKey("BillingAddress", on_delete=models.SET_NULL, blank=True, null=True) coupon = models.ForeignKey("Coupon", on_delete=models.SET_NULL, blank=True, null=True) preproccessed = models.BooleanField(default=False) dispatched = models.BooleanField(default=False) delivered = models.BooleanField(default=False) Refund_requested = models.BooleanField(default=False) Refund_granted = models.BooleanField(default=False) Paid_price = models.FloatField(default=0) The user model is the standard django.contrib.auth.models user model -
Django-Filter: Method argument to filter two attributes
I created a model with a way to grant a credit with some attributes like customer id, amount of credit, result of the credit, due date, created date. for the purpose of the app, I should filter the credit's period of the validity. Then I create a method in the filter like this: period_of_validity = filters.BooleanFilter( method="period_of_validity_filter", help_text="Get the period of validity of the credit according to the remaining days to the due date", ) and the method is: def period_of_validity_filter(self, queryset, name, value): result = queryset.filter( Q(result=CreditResult.GRANTED) | Q(due_date__gt=datetime.date.today())) return result However, I am not sure if the two Q are correct in order to find the granted credits and the credits with a due date greater than equal today. I give thanks for your help. -
Access local vagrant VM through a Django app running locally
Context: I am playing around with Django and Vagrant and I would like to see if I can have them interact with each other where a Django app running locally can access a local Vagrant VM. I have a Django app that I'm running locally using python manage.py runserver and I have a Vagrant VM that is up and running somewhere on my local machine in path/to/local/vagrant/vm. I would like to ssh and/or execute commands on the aforementioned local Vagrant VM through the Django app. Is that such thing possible? If so, how? If not, then how can I achieve something similar where I can have a Django app interact with a local VM. -
Is it possible to have a OneToOneField in Django that's only null=True in one direction?
Is it possible to create a OneToOneField in Django that is only null=True in one direction? Ex: class Building(models.Model): ... class Roof(models.Model): building = models.OneToOneField(...) ... A building doesn't technically need to have a roof. Plenty of unfinished buildings don't have them. But you can't have a roof without a building. Also, a building can only have one roof, and a roof can only be on one building, hence OneToOneField. -
Why is my Django data migration from ForeignKey field to OneToOneField not working?
I have some models with a ForeignKey field that points to another model: class Specimen(models.Model): ... class ResultA(models.Model): specimen = models.ForeignKey(Specimen, on_delete=models.CASCADE, ...) ... class ResultB(models.Model): specimen = models.ForeignKey(Specimen, on_delete=models.CASCADE, ...) ... At some point, I realized that each specimen will only ever have zero or one of each type of result, so it probably makes sense to turn that into a OneToOneField. The plan is to: Create an additional specimen_new field that's a OneToOneField on each result Create a data migration that will move the data from the ForeignKey field to the OneToOneField field Delete the ForeignKey field Rename the new specimen_new OneToOneField to just specimen Update all the code references to use the new OneToOneField properly Step 1 was pretty simple: class Specimen(models.Model): ... class ResultA(models.Model): specimen = models.ForeignKey(Specimen, on_delete=models.CASCADE, ...) specimen_new = models.OneToOneField(Specimen, on_delete=models.CASCADE, ...) ... class ResultB(models.Model): specimen = models.ForeignKey(Specimen, on_delete=models.CASCADE, ...) specimen_new = models.OneToOneField(Specimen, on_delete=models.CASCADE, ...) ... I'm stuck on step 2 - creating the data migration. Right now, it looks like this: from django.db import migrations def migrate_results(apps, schema_editor): # Get the model Specimen = apps.get_model('ahs', 'Specimen') # Update every specimen for specimen in Specimen.objects.filter(): for field in Specimen._meta.get_fields(): # Look for fields that …