Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dockerize Django Websocket Url not found
I have a project with Django using Websocket and I'm using a docker. I have configuration named local.yml and used uvicorn and channels. When I started to build my docker, the http request works fine but my websocket urls is not found 404 error. Here is my local.yml: version: "3" services: django: &django build: context: . dockerfile: ./compose/local/django/Dockerfile image: api_local_django container_name: api_local_django platform: linux/x86_64 restart: always depends_on: - postgres - redis volumes: - .:/app env_file: - ./.envs/.production/.django - ./.envs/.local/.postgres ports: - "8000:8000" # command: /start command: uvicorn config.asgi:application --host 0.0.0.0 # command: uvicorn config.asgi:application --bind 0.0.0.0:8000 --timeout 300 --chdir=/app # /usr/local/bin/gunicorn config.wsgi --bind 0.0.0.0:5000 --timeout 300 --chdir=/app postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: api_production_postgres container_name: api_local_postgres volumes: - ./api_local_postgres_data:/var/lib/postgresql/data - ./api_local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres ports: - "5432" redis: image: redis:6 container_name: api_local_redis celeryworker: <<: *django image: api_local_celeryworker container_name: api_local_celeryworker depends_on: - redis - postgres ports: [] command: /start-celeryworker celerybeat: <<: *django image: api_local_celerybeat container_name: api_local_celerybeat depends_on: - redis - postgres ports: [] command: /start-celerybeat flower: <<: *django image: api_local_flower container_name: api_local_flower ports: - "5555:5555" command: /start-flower Now above, I tried to start using uvicorn and it has no errors. Now here is my asgi file which handles the http … -
Django Session management with Vercel
I have a Django web app currently hosted on Vercel that displays a users top artists and tracks. It utilises the Spotify API to retrieve the access token and request the data. In my app the access token is saved using a class however I've come to a problem where if a user does not enter the site via the main page eg: spotify-app.vercel.app/ and goes straight to spotify-app.vercel.app/top-tracks they see the data of the last person who logged in because the token is saved in the class. I'm also assuming this site would not work when multiple users are on. How would I go about storing the access token for just the current user rather than saving it on the server. I have tried using the sessions library however vercel does not support it. How else can i manage my user sessions? class: class SpotifyAPI(object): access_token = None access_token_expires = datetime.datetime.now() access_token_did_expire = True client_id = None client_secret = None scope = None redirect_uri=None token_url = "https://accounts.spotify.com/api/token" def __init__(self, client_id, client_secret,redirect_uri,scope, *args, **kwargs): super().__init__(*args, **kwargs) self.client_id = client_id self.client_secret = client_secret self.redirect_uri = redirect_uri self.scope = scope def is_token_expired(self): # Check if the access token has expired access_token = … -
Django - How to translate static choices of a form field
I have a form to update the details of the user in a multilingual text. In the dropdown for sex, it does not translate the choice of sex as below: I tried using the gettext_noop in the model.py file for the choices. I see them in the .po file. Still it doesn't work. What am I doing wrong? model.py from django.utils.translation import gettext_noop Account_sex = [('male',gettext_noop('Male')),('female',gettext_noop('Female'))] #List of tuples with choices. First one is what's stored in DB and second what is shown in html. class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) email = models.EmailField(max_length=100, unique=True) sex = models.CharField(max_length=10, blank=True, null=True, choices=Account_sex, default='male') view.py @login_required(login_url='login') def edit_profile(request): if request.user.is_authenticated: current_user = Account.objects.get(id=request.user.id) form = EditProfileForm(request.POST or None, instance=current_user) if form.is_valid(): form.save() messages.success(request,("Your profile has been updated!")) return redirect('dashboard') return render(request, 'accounts/edit_profile.html',context={'form':form}) # else: messages.success(request,('You must be logged in!')) return redirect('login') edit_profile.html <div class="col col-auto form-group"> <label>{% trans "Sex" %}</label> {{ form.sex }} </div> django.po #: .\accounts\models.py:44 msgid "Male" msgstr "Hombre" #: .\accounts\models.py:44 msgid "Female" msgstr "Mujer" -
How to reuse Django Model Form with changed labels?
Inside a Django app I have a Person model that I want to use in a form to capture both student and teacher data. The fields are identical in both forms, but the labels should be different. How can I change the labels before passing the form to the template? The class for the form with default labels for student_form: class ProfileForm(forms.ModelForm): class Meta: model = Person fields = ('first_name', 'last_name', 'email') labels = { 'first_name': label("Student's Name"), 'last_name': label("Student's Surname") } I tried to change the labels attributes as per below, but Django says that ProfileForm has no attribute 'labels'. def add_profile(request): teacher_form = ProfileForm(prefix = 'teacher') teacher_form.labels['first_name'] = label("Teacher's Name") teacher_form.labels['last_name'] = label("Teacher's Surname") return render(request, "school/add_profile.html", { "profileform" : teacher_form }) Is there a way to access the Meta class to change its attributes? -
CSRFTOKEN not defined on incognito
I am working on an application that has the backend on django and the frontend on react. The problem I am facing now is csrftoken. All my forms are submitted on using a normal browser but if I use Incognito mode I cannot submit the request because the csrftoken is not found. The function I use to receive the csrftoken: const getCsrfToken = () => { const value = `; ${document.cookie}`; const parts = value.split(`; csrftoken=`); if (parts.length === 2) return parts.pop().split(';').shift(); }; I know I can use @csrf_exempt on views but I want to keep my app secure. Is there any way to generate that csrftoken even if users use incognito mode? -
my django server is stopping without an error appearing
My Django server is stopping without an error appearing, I am making an application that captures the microphone and transcribes and translates everything that is said using the Google speech-to-text and Google translate APIs and I want to display the output of the API on a web page. I'm having difficulty displaying the return from my api on the django server I tried with ajax and it didn't work I need it to update each sentence simultaneously this is the python code of the application from django.shortcuts import render import speech_recognition as sr from googletrans import Translator import threading import logging logger = logging.getLogger(__name__) translation_running = False def paginaInicial(request): global translation_running if request.method == 'POST': if translation_running: translation_running = False else: translation_running = True translation_thread = threading.Thread(target=perform_translation) translation_thread.start() return render(request, "index.html") def perform_translation(): global translation_running r = sr.Recognizer() mic = sr.Microphone() while translation_running: with mic as source: print("Diga algo...") r.adjust_for_ambient_noise(source) audio = r.listen(source) try: audio_text = r.recognize_google_cloud(audio, credentials_json='', language='pt-BR') print("Texto transcrito:", audio_text) translation_result = translate_text(audio_text) if translation_running: logger.info(f'Texto Original: {audio_text}') logger.info(f'Texto Traduzido em Inglês: {translation_result["translated_text_en"]}') logger.info(f'Texto Traduzido em Espanhol: {translation_result["translated_text_es"]}') except sr.UnknownValueError: print("Não foi possível transcrever o áudio.") except sr.RequestError as e: print("Erro na requisição à API: {0}".format(e)) except Exception … -
Nginx Removing First Sections Of URL
I have Django/Django-CMS website and I use Nginx to proxy pass Gunicorn and load static files. Nginx rules of Django and my template js plugins are getting confused by the including style of functions of theme. Basically theme loads only a functions.js file and all the rest of script files are called from that file. The problem is that, while in the Homepage 'abctasarim.com/static/bootstrap.plugins.js', if I click about-us link, it is becoming 'abctasarim.com/en/about-us/static/bootstrap.functions.js' and I get 404 error code. I tried to find a solution to make it in better way but now I am a little bit lost in the answers. In my nginx.conf, my workaround is as below, which I am sure that can be solved with regex without overwriting the rest of urls. location /static/ { autoindex on; alias /home/ytsejam/public_html/luftchem/luftchem/static_cdn/; expires 365d; access_log off; #add_header Cache-Control "public"; #proxy_ignore_headers "Set-Cookie"; } location /en/about-us/static/ { autoindex on; alias /home/ytsejam/public_html/luftchem/luftchem/static_cdn/; expires 365d; access_log off; #add_header Cache-Control "public"; #proxy_ignore_headers "Set-Cookie"; } How can I write a Regex to loose to parts of url before the static part in sub urls? Thanks -
When calculating integers (without decimal places), is there no difference between integer, float, and decimal?
I know that I should use models.DecimalField when I need an exact result, such as calculating a currency. In my model, I have a "quantity" field that needs to be calculated frequently. However, this "quantity" field is an integer, no decimal calculations are required. In this case, does it make any difference whether I use models.DecimalField, models.FloatField, or models.IntegerField? -
Looking for button to navigate to login page in python using justpy
I'm using justpy to make a small scale management system, its a framework for developing web apps in python without css/html/js. The menu displays itself but none of the buttons work.The following is the code I have so far: import justpy as jp class LoginPage(jp.WebPage): def __init__(self): super().__init__() form_div = jp.Div(classes='w-64 mx-auto mt-10', a=self) self.username_input = jp.Input(placeholder='Username', classes='w-full mb-2 p-2', a=form_div) self.password_input = jp.Input(placeholder='Password', type='password', classes='w-full mb-2 p-2', a=form_div) self.login_button = jp.Button(text='Login', classes='w-full bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded', a=form_div) class MenuPage(jp.BaseWebPage): def __init__(self): super().__init__() self.menu = jp.Div(classes='flex justify-around p-4 bg-blue-500 text-white', a=self) self.login_button = jp.Button(text='LOGIN', classes='p-2 hover:bg-blue-700', a=self.menu, click=self.go_to_login) self.home_button = jp.Button(text='HOME', classes='p-2 hover:bg-blue-700', a=self.menu) self.forums_button = jp.Button(text='FORUMS', classes='p-2 hover:bg-blue-700', a=self.menu) self.help_button = jp.Button(text='HELP', classes='p-2 hover:bg-blue-700', a=self.menu) def go_to_login(self, msg): self.delete() # Remove the menu from the page a = LoginPage() a.show() # Add the login page to the page jp.justpy(MenuPage) I'm trying to create a dashboard with the menu options HOME, LOGIN, FORUMS, HELP. I have implemented the logic of the login button but can't get it to work. I can't get the LOGIN button to work, I tried making two different classes, one for the menu and the other for the login but still no luck. … -
Direct assignment to the reverse side of a many-to-many set is prohibited. Use category.set() instead
a problem on M2M Django assignment this is where i get the error : def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.category = validated_data.get('category', instance.category) instance.price = validated_data.get('price', instance.price) instance.description = validated_data.get('description', instance.description) instance.image = validated_data.get('image', instance.image) instance.active = validated_data.get('active', instance.active) instance.deleted = validated_data.get('deleted', instance.deleted) instance.parent_category.set(validated_data.get('parent_category')) instance.save() return instance i tried "add" method too but it gets same error -
How do I obtain Django's user password reset URL within Python (i.e., not within a template)
I am generating a variable text in Python where I need to inject the URL for the user to navigate to after they requested password reset. I.e., I am building a string for content of an email and thus cannot use the standard template language {% url 'password_reset_confirm' uidb64=uid token=token %} What I have so far is: def myFunction(toEmail_): #-- find user to send the email to user = User.objects.get(email=toEmail_) #-- build email text resetUrl = "????" #TODO: WHAT TO PUT IN HERE? emailText = "Hi, please reset your password on this url {}".format(resetUrl) #-- send email with the text ... How do I obtain this reset url in Python? -
Django-admin display decorator sorting by multiple columns
In my database model, I have last and first name. In the django-admin site, I want to display "Lastname, Firstname" and have this column sortable. For this, I'm using the @admin.display decorator in my admin.ModelAdmin class. This decorator takes an ordering parameter which can be a string, referencing a model field name to sort by, for example: @admin.display(description = "Full name", ordering = "last_name") def full_name(self, obj): return f"{obj.last_name}, {obj.first_name}" However, this will only sort by last_name, obviously, and therefore people with the same last name will end up in arbitrary order. I've tried: @admin.display(description = "Full name", ordering = ["last_name", "first_name"]) Or using a list instead of a tuple, but this fails ("'tuple' object has no attribute 'startswith'"). I searched for this and found my exact question unanswered here: https://forum.djangoproject.com/t/how-to-tell-admin-display-decorator-to-order-the-results-by-two-columns/21418 Also in this post: Django-admin order by multiple fields someone suggests that the intuitive list syntax would work with "ordering", but this does not seem to work inside the decorator. -
Unwanted 'email' displayed using Validation Error for Password Reset Form
I'm working on implementing password reset functionality in Django. I wanted to create my own message to the user using the ValidationError class, and I succeeded in doing so. However, unfortunately, an unwanted 'email' is displayed along with this message. forms.py: class ResetPasswordForm(PasswordResetForm): def __init__(self, *args, **kwargs): super(ResetPasswordForm, self).__init__(*args, **kwargs) email = forms.EmailField(max_length=255, label='E-mail Address', required=True, validators=[ValidationError], widget=forms.TextInput(attrs={ 'id': 'register-email', 'label': 'required', 'type': 'text', 'placeholder': 'Your E-mail Address' })) def clean_email(self): email = self.cleaned_data['email'] if not User.objects.filter(email__iexact=email, is_active=True).exists(): raise ValidationError(f"This address e-mail doesn't exists.") return email enter image description here enter image description here HTML: {% extends 'core/base.html' %} {% block title %}{{ title }}{% endblock %} {% block content %} <div id="user-form"> <form class="login-form" method="post" action=""> {% csrf_token %} <div class="form-row"> <div class="input-wrapper"> <label>{{ reset_form.email.label }}</label> {{ reset_form.email }} {{ reset_form.errors }} </div> </div> <div class="submit-row"> <button class="btn" type="submit">Send E-mail</button> </div> </form> </div> {% endblock %} How can I remove it? This knowledge will definitely come in handy in the future. -
Django - filter two M2M fields to one model for specifis condition happening in single object
The problem that I am facing is quite complicated but maybe the answer is simple. So I have a model with two M2M fields to the same model, and I want to filter only these objects which are in 1st field but are not in 2nd. class Model1(models.Model): ... class Model2(models.Model): rel1 = models.ManyToManyField( Model1, related_name="rel1" ) rel2 = models.ManyToManyField( Model1, related_name="rel2" ) and now I want to get objects which for single Model2 objects are only in rel1 not in rel2. For example obj2_1 = Model2(rel1=[obj1, obj2, obj3], rel2=[obj1, obj2]) obj2_2 = Model2(rel1=[obj1, obj3], rel2=[obj3]) Model2.filter(obj_in_rel2_but_not_in_rel1=obj3) -> obj2_1 where object1,2,3 are Model1 instances and obj2_1, obj2_2 are Model2 instances. I would like to get database query, not getting all objects and then making some python filter on that. I am expecting to get some annotation or something similar. It would be even better if I could get the result from perspective of Model1 (Model1.objects.filter(...)) -
Docker compose builds unknown warnings, tables and roles
I need help understanding why my Django App is giving me a long long while hosting the database. The boilerplate is available here: https://github.com/trouchet/tarzan. Please, I am studying and want a remote job, and not be a local attendant in a cafe. As you can see, the app builds and ups as expected, with the following issues, from my perspective: Unknown warning: WARN[0000] The "d" variable is not set. Defaulting to a blank string; Unknown database roles and tables: It starts with the snippet below and goes beyond with several unknown issues. tarzan-memory | 2023-09-13 17:48:28.990 UTC [75] FATAL: password authentication failed for user "newrelic" tarzan-memory | 2023-09-13 17:48:28.990 UTC [75] DETAIL: Role "newrelic" does not exist. tarzan-memory | Connection matched pg_hba.conf line 99: "host all all all md5" tarzan-memory | 2023-09-13 17:48:36.180 UTC [71] ERROR: relation "qrtz_scheduler_state" does not exist at character 15 tarzan-memory | 2023-09-13 17:48:36.180 UTC [71] STATEMENT: SELECT * FROM QRTZ_SCHEDULER_STATE WHERE SCHED_NAME = 'MetabaseScheduler' tarzan-memory | 2023-09-13 17:48:36.180 UTC [72] ERROR: relation "qrtz_triggers" does not exist at character 67 tarzan-memory | 2023-09-13 17:48:36.180 UTC [72] STATEMENT: SELECT TRIGGER_NAME, TRIGGER_GROUP, NEXT_FIRE_TIME, PRIORITY FROM QRTZ_TRIGGERS WHERE SCHED_NAME = 'MetabaseScheduler' AND TRIGGER_STATE = $1 AND NEXT_FIRE_TIME <= $2 … -
wrong with CELERY_BEAT_SCHEDULER in setting.py
setting.py # celery CELERY_TIMEZONE = "UTC" CELERY_BROKER_URL = "redis://127.0.0.1:6379" CELERY_ACCEPT_CONTENT = ["application/json"] CELERY_RESULT_SERIALIZER = "json" CELERY_TASK_SERIALIZER = "json" CELERY_RESULT_BACKEND = "django-db" # celery-beat CELERY_BEAT_SCHEDULER = "django-celery-beat.schedulers:DatabaseScheduler" INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "rest_framework_simplejwt", "corsheaders", "celery", "django_celery_results", "django_celery_beat", # Custom apps ... ] So I want to run my celery-beat: celery -A config beat -l INFO where config is my project's name And than I have error message: ModuleNotFoundError: No module named 'django-celery-beat' Celery.py "clear_spent_in_categories_every_month": { "task": "category.tasks.clear_all_spent", # "schedule": crontab(day_of_month="1", hour="0", minute="0") "schedule": crontab(hour="4", minute="40") } }``` I tried to restart my IDE, server, reinstall celery, checked my INSTALLED_APPS, and I don't know, why it doesn't work. But if I delete setting CELERY_BEAT_SCHEDULER = "django-celery-beat.schedulers:DatabaseScheduler", it's works with celery.beat.PersistentScheduler -
Cloud run logs in GCP shows that web app is running successfully but the generated domain name is never reachable
I have followed documentation instructions and have been able to deploy a django app connected to a postgresql database. The issue is that the deployment does result a success, and looking at the instance logs here is what is shown: [![enter image description here][1]][1] I also tried with gunicorn and it seems to have the same result. And configured the networks to allow all and allow unauthenticated invocations. What can be the issue here? [1]: https://i.stack.imgur.com/gUCSz.png -
Django Fixtures minimal subset that respects foreign key constraints
I want to set up a test DB for my Django project in order to do some propert testing. Sadly our DB is huge and very interconnected. This means using the full DB for testing is very slow if django needs to import a fixture with millions of lines of data at the start. However creating a suitable subset of Data seems to be problematic too, because there are so many foreign key constraints. I used this script to create a fixture: from itertools import chain from django.db.utils import DEFAULT_DB_ALIAS from django.core import serializers from django.contrib.admin.utils import NestedObjects from models import EntryTable collector = NestedObjects(using=DEFAULT_DB_ALIAS) # database name collector.collect([EntryTable.objects.get(pk=1)]) objects = list(chain.from_iterable(collector.data.values())) objects.reverse() with open("search/fixtures/TestSkeleton.json", "w") as f: f.write(serializers.serialize("json", objects)) However it seems that this does not resolve all dependencies. For example EntryTable is pointed to by a Table A, and A is pointed to by a table ALinkB, which also points to a table B. The relevant Objects in A and ALinkB are in the fixture however table B was not. Therefore loading this fixture resulted in violated foreign key constraints. Does someone know what I am missing? -
why urls will append after last url in django
when i click on on about or another tabs for first time everything is good but when i click a tab again after another tab its url appends to last url.strong text urls: from .views import * app_name = 'root' urlpatterns = [ path("",home,name='home'), path("about/",about,name='about'), path("contact/",contact,name='contact'), path("trainers/",trainers,name='trainers') ]``` html: ``` <li><a class="active" href="{% url 'root:home' %}">Home</a></li> <li><a href="{% url 'root:about' %}">About</a></li> <li><a href="{% url 'course:courses' %}">Courses</a></li> <li><a href="{% url 'root:trainers' %}">Trainers</a></li> <li><a href="{% url 'root:contact' %}">Contact</a></li>``` ------------------------------------------------------------------------ -
Creating a django model for a completely different set of users
I created a model called Driver, which isn't inheriting from the in-built User model every django project comes with. Another model I created inherits from it. Each driver has a name, email and phone number. The model doesn't inherit the set_password() or check_password() functions from the User model so I had to make some additions to the model to save the hashed password. However, any time I test a login, it doesn't work, on account of the typed password not matching the hash in the database. from django.db import models from django.contrib.auth.hashers import make_password class Driver(models.Model): name = models.CharField(max_length= 50) phone_number = models.CharField(max_length=15) email = models.EmailField(unique=True, null=True) password = models.CharField(max_length=50) def __str__(self): return self.name def save(self, *args, **kwargs): # Hash the password before saving self.password = make_password(self.password) super().save(*args, **kwargs) def check_password(self, password): return self.password == password How can I create a function to properly compare the typed passwords to the hashed version in the database? Or am I going about this all wrong? -
Django : Streaming data with PyPDF2
When the pdf is generate , i would like to avoid saving a file to disk : output_pdf = PdfWriter() for i in range(len(input_pdf.pages)): page = input_pdf.pages[i] if i == 0: page.merge_page(text_pdf.pages[0]) output_pdf.add_page(page) with open('assets/media/consignes.pdf', 'wb') as f: output_pdf.write(f) f.close() return FileResponse(open('assets/media/consignes.pdf','rb'), as_attacheement=False, content_type='application/pdf') -
Django rest framework add image with react and axios
I am trying to make a form where a user uploads a post which is just a picture. I am using django rest framework for api and react for frontend. const formData = new FormData() const savePost = () => { axios.post('http://127.0.0.1:8000/create_post/', formData, { headers: { "Content-Type": "multipart/form-data", }, }) } const handleChange = (e) => { if (e.target.files && e.target.files.length > 0) { setSelectedFile(e.target.files[0]) formData.append("image", e.target.files[0]); } <form onSubmit={savePost}> <input type="file" onChange={handleChange} /> <input type="submit" /> </form> But when I press submit a new instance is added but the image is just /media/ without the actual image. -
Testing new django database migrations on filled live database or freshly created one?
I'm currently working on a django project running on docker with an sqlite3 database. We are using Gitlab as Version Control (including gitlab CI system). Im just testing for now and we have not deployed yet/are not live, but i have some issues thinking of the final workflow after deploying. Regarding the CI system, i was searching for a while now, but i didn't find an accurate answer on how the migrations and the database itself are tested in the CI system and how a proper development workflow looks like. Im mainly concerned with the following point: Since all our migration files are under version control from the first start of the database (we will start with a fresh db.sqlite when going live). Is it then necessary to check every following migration on the (filled) live database (or latest backup?)? Or can i just create a fresh database for every migration check (when model changes are made). To give an example maybe: Im a developer and make changes to some models of the project. Is it ok now for testing to create a fresh database, then firstly apply the old migrations to the database, then 'makemigrations' for the new changes … -
save_screenshot() vs get_screenshot_as_file() in Selenium in Python
I took 2 screenshots of Django Admin with save_screenshot() and get_screenshot_as_file() as shown below. *I use Django, pytest-django and Selenium: def test_1(live_server): driver = webdriver.Chrome() driver.get(("%s%s" % (live_server.url, "/admin/"))) driver.save_screenshot("admin.png") # Here def test_1(live_server): driver = webdriver.Chrome() driver.get(("%s%s" % (live_server.url, "/admin/"))) driver.get_screenshot_as_file("admin.png") # Here Then, I got the same screenshots as shown below: admin.png: So, what is the difference between save_screenshot() and get_screenshot_as_file() in Selenium in Python? -
How to deal with unresolved related model during test migrations
I have an app in production that is very okay. I am currently adding unit tests but so far the tests are failing because of a migration-related error during the creation of the test database. ValueError: Related model 'my_app.my_model' cannot be resolved Here is the full Stack Trace Some background info: I had a model MyModel that was a ForeignKey on other models in different apps. I renamed the model to NewModel. I also renamed all the ForeignKeys from my_model to new_model. Django migrations asked whether I renamed the model, I accepted, and I have verified the renaming was done correctly in the migration files. My test case is something like this: class DoerTestCase(TestCase): @classmethod def setUpTestData(cls): A.objects.create(title='Test A') NewModel.objects.create(title='Test New Model') def setUp(self): a = A.objects.first() new_model = NewModel.objects.first() B.objects.create(a=a, new_model=new_model) def test_doer(self): b = B.objects.first() ... How can I resolve this without possibly interfering with the existing migrations?