Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FileField in Django does not send file to its form request
I have a Django form where I upload an image through an input type file. class Form(forms.Form): photo = forms.FileField( label="Photo", widget=forms.FileInput( attrs={ 'class': 'form-control', } ) ) I wrote the next view: def upload(request): context = {} if 'photo' in request.POST: form = Form(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES["photo"]) else: print(form.errors) else: form = Form() context['form'] = form return render(request, 'app/upload.html', context) def handle_uploaded_file(file): with open('app/upload/'+file.name, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) When I send the form the request does not recieve any file, even if I loaded a file before. I am able to show by javascript jpeg files loaded when the field has changed. So the field is loading files but is not sending theme in the request. Form does not check the validation form.is_valid(): it says it is required even when I have uploaded a file .jpeg Error shown in print(form.errors): <ul class="errorlist"><li>photo<ul class="errorlist"><li>This field is required.</li></ul></li></ul> I leave my template form here: <form action="" method="post" id="search_face_form" style="width: 100%;"> {% csrf_token %} <div class="row"> <div class="col-sm-4"> <div class="input-group-sm mb-4"> <label for="floatingInput">Archivo de búsqueda</label> {{ search_form.face }} {{ search_form.face.errors }} </div> </div> <div class="col-sm-6"> <img id="search_face_img" src="{% static 'cameras_admin/img/not_found.jpg' %}" style="display: none; max-height: 25vh;"> </div> <div … -
Confirming the Updated User Email address in Django with a Boolean
Am creating profile Update. It works fine and l can change the Username and the Email. But l would like to confirm the New submitted email by sending an otp or a verification link , so that a user can verify that email. I have been looking for the solution of doing it but l just found one post on Stackoverflow, whereby someone is suggesting that you can deactivate the user and send a confirmation email and then activate him or her again But am asking; ls it possible to create a model with a Boolean field and connect that model to a User model, so that l can set that Boolean field to send a verification code to User who changed his or her email Address? email_comfirm.py #email comfirm model class EmailComfirm(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE) is_comfirmed=models.BooleanField(default=True) active_otp=models.CharField(max_lenght=8) If possible; How can l phrase that model and it's function? I would like to call that Boolean to check if the email is changed, and if changed, turns off or set false and process the verification link after confirming the email it sets true. is_comfirmed() = False Secondly; How am l going to confirm that email? To me l would like to … -
My test fails due to sending an invalid file
Initially I will show you my action in my view: def add_photo_to_object(self, request, object_id, pk=None): uploaded_file = request.data.get('image') print(uploaded_file.size) request.data['user_owner'] = request.user.id print(request.data) serializer = self.action_serializers['add_photo_to_object'](data=request.data) serializer.is_valid(raise_exception=True) serializer.save() ... The results of these prints are - 0 and <QueryDict: {'name': ['small'], 'image': [<InMemoryUploadedFile: mock_image.jpg (image/jpg)>], 'user_owner': [1]}> My test looks like this: def test_add_photo_to_object(authorized_client, objects): checkpoint = objects[0] questionnaire = checkpoint.element.first() url = reverse('checkpoint-add-photo-to-object', kwargs={'pk': checkpoint.id, 'object_id': object.id}) uploaded = SimpleUploadedFile('mock_image.jpg', b'mock_content' * 1000, content_type='image/jpg') photo_data = {"name": "small", "image":uploaded} response = authorized_client.post(url, data=photo_data, format='multipart') response_data = response.json() assert response.status_code == status.HTTP_201_CREATED, response_data Well I always end up getting the error that AssertionError: {'image': ['Sent file is empty.']}. Please advise me how to avoid this error and Mock image such send. I can't use Pillow or store the test image on the server -
--headless vs --headless=chrome vs --headless=new in Selenium
I'm learning Selenium with Django and Google Chrome. *I use Selenium 4.11.2. Then, I tested with --headless, --headless=chrome and --headless=new as shown below, then all work properly: from django.test import LiveServerTestCase from selenium import webdriver class TestBrowser(LiveServerTestCase): def test_example(self): options = webdriver.ChromeOptions() options.add_argument("--headless") # Here driver = webdriver.Chrome(options=options) driver.get(("%s%s" % (self.live_server_url, "/admin/"))) assert "Log in | Django site admin" in driver.title from django.test import LiveServerTestCase from selenium import webdriver class TestBrowser(LiveServerTestCase): def test_example(self): options = webdriver.ChromeOptions() options.add_argument("--headless=chrome") # Here driver = webdriver.Chrome(options=options) driver.get(("%s%s" % (self.live_server_url, "/admin/"))) assert "Log in | Django site admin" in driver.title from django.test import LiveServerTestCase from selenium import webdriver class TestBrowser(LiveServerTestCase): def test_example(self): options = webdriver.ChromeOptions() options.add_argument("--headless=new") # Here driver = webdriver.Chrome(options=options) driver.get(("%s%s" % (self.live_server_url, "/admin/"))) assert "Log in | Django site admin" in driver.title My questions: What is the difference between --headless, --headless=chrome and --headless=new? Which should I use, --headless, --headless=chrome or --headless=new? -
How to insert placeholder in Django Admin text input
I've tried three methods, first as described in how-to-add-placeholder-text-to-a-django-admin-field and in the docs from django import forms class AppointmentAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): kwargs['widgets'] = { 'name': forms.TextInput(attrs={'placeholder': 'Type here'}) } return super().get_form(request, obj, **kwargs) Then the method described in django-add-placeholder-text-to-form-field, slightly altered to get around Python errors. class AppointmentAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) form.base_fields['customer'].widget.attrs["placeholder"] = "Type here" return form Finally, using formfield_overrides: class AppointmentAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: { "widget":forms.TextInput(attrs={'placeholder':'Type here'})}, } None of these are working. I must be overlooking something simple? The relevant portion of models.py: class Appointment(models.Model): customer = models.ForeignKey(Customer, blank=False, null=True, default=None, on_delete=models.CASCADE, related_name='appointments') -
how to write test in django to check code fallback behavior to the database from redis corectly?
I have a python-django code. the code take inscode as input and check the redis and return blong data. in case redis is down or no data in it code fallback to database and read data from there. then i write integration test for this code in pytest check behave of the code in multiple cases on of the cases is that i want to mock redis and raise an error to disable it and see code can fallback to database and return data and in end return data should assert equal with data i got from redis before. main code: class GetOrderBook(APIView): def get(self, request, format=None): # get parameters inscode = None if 'i' in request.GET: inscode = request.GET['i'] if inscode != None: try: #raise ('disabling redis!') r_handle = redis.Redis( redis connection) data = r_handle.get(inscode) if data != None: return Response(json.loads(data)) else: print('GetOrderBook: data not found in cache') except BaseException as err: print(err) orderbook = OrderBook.objects.filter( symbol__inscode=inscode).order_by('rownum') if len(orderbook) > 0: data = OrderBookSer(orderbook, many=True).data data_formatted = # here making bnew format for row in data: # new format return Response(data_formatted) else: return Response({'Bad Request': 'invalid input'}) return Response({'Bad Request': 'incomplete input data'},) and this is test for part … -
SSO authentication not working on cross-domain requests
I am trying to enable SSO on my website. The backend is on Django hosted on a different domain and frontend is on React on a different domain. The backend is making Djoser package to handle social authentication. The sessionId which I receive in the form set-cookie header is not getting saved in browser cookies even though Access-Control-Allow-Credentials is true due to which SSO is failing. The same is working if my backend and frontend are on the same domain. Is there any solution to this? I am expecting SSO authentication on cross domain architecture but it is failing because session Id is not getting saved in browser cookies even though Access-Control-Allow-Credentials were enabled. -
Azure mobile app service keep getting it's pyodbc library version change without any actions
We have a Django/React mobile app that is hosted in Azure with the an app service plan (python 3.8.17) on Linux. 2-3 times a week, it stops working because the version of the pyodbc changes without any action on our side. We need to log into the SSH and switch the library libmsodbcsql-17-10.so.4.1 to libmsodbcsql-17-10.so.2.1 and then everything comes back to normal. What can cause this issue ? We checked if it was planned maintenance or any other Azure service that took action of some sort but couldn't find anything. -
Django unittest. Extract pk of a created object using .post method
Im studying some Python courses and i've got a project fully dedicated to unittest and pytest. The problem I have here is that i use the client.post method to create a note. My reviewer asked me get the note i just created using its pk. Have no idea how to do it. This is the code i currently have : def test_user_can_create_notes(self): response = self.auth_another_author.post(URL_NOTES_ADD, data=self.form_data) self.assertRedirects(response, URL_NOTES_SUCCESS) self.assertTrue(Note.objects.filter( title=self.form_data['title'], text=self.form_data['text'], slug=self.form_data['slug']).exists()) So i need to get the note object by pk and then check with assertEqual if its fields match the self.form_data fields I also tried getting the freshly created object using get and filter by the slug field. But that did not convince my reviewer -
How To Change LDAP Variables?
I need to change django-auth-ldap variables such as AUTH_LDAP_URI with dynamic inputs from user. How do I manipulate these variables in the memory? I tried changing imported variables expecting library automatically detects it. -
IntegrityError FOREIGN KEY constraint failed [In django project ]
While adding user data in DB through a form I created I got this error integrity error at \add_emp and it says foreign key constraint failed I tried deleting dbsqlite3 files, migrations files, and pychache files but that did not work please tell me where I am wrong it's my first time getting this error. enter image description here This is shown after submitting This is the Models.py code from django.db import models # Create your models here. class Department(models.Model): name = models.CharField(max_length=100,null=True) location = models.CharField(max_length=100) def __str__(self): return self.name class Role(models.Model): name = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Employee(models.Model): first_name = models.CharField(max_length=100, null=False) last_name = models.CharField(max_length=100,null=True) dept = models.ForeignKey(Department, on_delete=models.CASCADE) salary = models.IntegerField(default=0,null=True) bonus = models.IntegerField(default=0,null=True) role = models.ForeignKey(Role, on_delete=models.CASCADE) phone = models.IntegerField(default=0,null=True) hire_date = models.DateField(null=True) def __str__(self): return "%s %s %s" %(self.first_name, self.last_name, self.phone) This is the views .py code # Create your views here. def index (request): return render(request,"index.html") def all_emp (request): context={"emps":Employee.objects.all(),"roles":Role.objects.all(),"departments":Department.objects.all()} return render(request,"all_emp.html",context) def add_emp(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] salary = int(request.POST['salary']) bonus = int(request.POST['bonus']) phone = int(request.POST['phone']) dept = int(request.POST['dept']) role = int(request.POST['role']) new_emp = Employee(first_name= first_name, last_name=last_name, salary=salary, bonus=bonus, phone=phone, dept_id=dept,role_id=role,hire_date = datetime.now()) new_emp.save() return … -
Which Certificate Authorirties can issue an X.509 certificate for document signing in PEM format?
I am looking to build a custom document signing solution in my Django application using PyHanko. I want to use the certificates from a CA for this purposes. However majority of CAs that I reviewed either offer the complete document signing service or they provide certificate as tokens/Yubikey. Only Digicert is the provider that I could find which allows to download the certificate and then use it manually. Are there any other CAs that allow to download a dcoument signing cert in PEM etc format? -
How can I load Deep learning model only once so that the problem of loading the model every time while calling API in Django is reduced?
I am trying to load the heavy pretrained model which size is larger than 1 GB though API using Django. The model is loaded every time I call API which is time consuming. What can be the solution for this ? I was expecting to load model only once and can use methods while calling API. -
DRF doesnt populate field label when using source
So, I have some model with few fields I want to expose over REST API: class MyModel(models.Model): field1 = models.TextField(verbose_name="Field 1") field2 = models.TextField(verbose_name="Field 2") and have corresponding serializer: class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('field1', 'field2') This way it works fine: using GET I retrieve fields values, and using OPTIONS I retrieve secondary fields information (e.g. if the field is required, help text, and label) The problem is that I don't want to expose real fields name, and I want to use some other name instead, for example: field1 and secondField. For that I modify my serializer: class MySerializer(serializers.ModelSerializer): secondField = serializers.CharField(source='field2') class Meta: model = MyModel fields = ('field1', 'secondField') Now I receive correct values on GET, but fields labels are wrong on OPTIONS: for second field I receive "Secondfield" instead of "Field 2" How do I get correct field label when using source? -
django session (i can't carry the data to the next page)
once the login successful , it redirect to the whmcs page and show the success message too but it's not show the first name and last name of the user why ?? please help me viewa.py ( `def login(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] api_url = 'https://www.chltech.net/manage/includes/api.php' api_username = 'XMBoFf3A3RvUCQnsJaQEHjQefx9W5FWC' api_password = '4yCdTGPvQWS2tnRFYS6CgIG7HMcmtLWZ' api_action = 'validatelogin' api_params = { 'username': api_username, 'password': api_password, 'action': api_action, 'responsetype': 'json', 'email': email, 'password2': password, } response = requests.post(api_url, data=api_params) if response.status_code == 200: data = response.json() if data['result'] == 'success': user_first_name = data.get('firstname', '') user_last_name = data.get('lastname', '') request.session['user_first_name'] = user_first_name # request.session['user_last_name'] = user_last_name print(user_first_name,user_last_name) messages.success(request , "login successful") return redirect('whmcs') else: messages.error(request, "Invalid email or password.") else: messages.error(request, f"Login failed: HTTP Error {response.status_code}") form = CustomAuthenticationForm() return render(request, 'login.html', {'form': form}) def whmcs(request): user_first_name = request.session.get('user_first_name', '') user_last_name = request.session.get('user_last_name', '') return render(request, 'whmcs.html', {'user_first_name': user_first_name, 'user_last_name': user_last_name})` ) whmcs.html ( <!DOCTYPE html> <html> <head> <title>Client Emails</title> </head> <body> {% block content %} <h1>Welcome, {{ user_first_name }} {{ user_last_name }}</h1> {% if messages %} {% for message in messages %} {% if message.tags == 'error' %} <div class="alter alter-danger"> {{message}} </div> {% else %} <div class="alert … -
django-livereload-server installation
I am new to django and trying to install django-livereload-server In the installation guide, somewhere says: You need to inject the loading of the livereload javascript. You can do this in one of two ways: Through middleware by adding 'livereload.middleware.LiveReloadScript' to MIDDLEWARE_CLASSES (probably at the end): MIDDLEWARE_CLASSES = ( ... 'livereload.middleware.LiveReloadScript', ) Through a templatetag in your base.html (or similar) template: {% load livereload_tags %} ... {% livereload_script %} For the first solution, I've noticed there is no MIDDLEWARE_CLASSE = () in the settings.py file (django 4.2.4). Theres only a MIDDLEWARE_CLASSE = [] list, and putting 'livereload.middleware.LiveReloadScript' in it does not work. (Live reload runs, but can't refresh the page.) Where should I put 'livereload.middleware.LiveReloadScript' to get it to work? Whats the instruction for the second solution? I don't see the base.html in my project/ app. Should I create it myself? Appreciate any help! Using: VSCode, django, enve, Installed packages: asgiref 3.7.2 beautifulsoup4 4.12.2 Django 4.2.4 django-livereload-server 0.4 dnspython 2.4.2 et-xmlfile 1.1.0 greenlet 2.0.2 pip 23.2.1 setuptools 63.2.0 six 1.16.0 soupsieve 2.4.1 sqlparse 0.4.4 tornado 6.3.3 typing_extensions 4.7.1 tzdata 2023.3 -
How to check if field in a table object is equal to specific string in django template language?
model name=ApplicationForm test_selection is one of the charfiled in ApplicationForm(table) views.py applied_student=get_object_or_404(ApplicationForm, dob=dob,id=app_id) i am using this query in view and sending this data to my template... I want to check if applied_student.test_selection=="selected" but its not working i tried using {% if student.test_selection =="selected" %} If worked {% endif %} i want to compare this filed with stored string value in table in djanog template -
Customizing JWT token claims in Django
I'm trying to customize my JWT token and what ever I do I got an error like this : ImportError: cannot import name 'MyTokenObtainPairView' from 'base.api.serializers' (D:\Anaraki\api\bakend\base\api\serializers.py) here is my serializers.py file: from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['username'] = user.username return token class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer my urls.py file: from django.urls import path from . import views from rest_framework_simplejwt.views import (TokenRefreshView, TokenObtainPairView) from .serializers import MyTokenObtainPairView # to customize the token we use this one insted . urlpatterns = [ path('',views.getRoutes), path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] I did everything's that doc said but I still got this ... error, please help me. -
In Django, which has faster and better performance beween ".filter(a).filter(b)" and "Q objects" and "or/and queries" and "keyword queries"
Simply put, what is the order of performance and speed among the following similar looking queries in the Django ORM? .filter(a).filter(b) instances = Model.objects.filter(a=A).filter(b=B) Q objects instances = Model.objects.filter(Q(a=A) & Q(b=B)) or/and queries instances = Model.objects.filter(a=A) & Model.objects.filter(b=B) keyword queries instnaces = Model.objects.filter(a=A, b=B) Thank you, and please leave any comments below. AND please don't copy and paste chatgpt or any other ai services. -
How to implement SignOut request NextAuth with Django REST API?
I am trying to create frontend on next js for my Django REST API. I use Next Auth for frontend auth and token auth for backend api. For login I used api for example www.mysite.com/login and I got token and user data, so for logout I used api endpoint example www.mysite.com/logout it is needed to pass token in headers. So how to implement logout? import NextAuth from "next-auth" import CredentialsProvider from "next-auth/providers/credentials" import api from "../baseaxios" const SIGN_IN_HANDLERS = { "credentials": async (user, account, profile, email, credentials) => { return true; }, }; const SIGN_IN_PROVIDERS = Object.keys(SIGN_IN_HANDLERS); const handler = NextAuth({ providers: [ CredentialsProvider({ name: 'Credentials', credentials: { username: { label: "Email", type: "email", placeholder: "Email" }, password: { label: "Password", type: "password" } }, async authorize(credentials, req) { const res = await api.post("/login", { body: JSON.stringify(credentials), headers: { "Content-Type": "application/json" } }) const user = await res.json() if (res.ok && user) { return user } return null } }) ], pages: { signIn: '/login', }, callbacks: { async signIn({user, account, profile, email, credentials}) { if (!SIGN_IN_PROVIDERS.includes(account.provider)) return false; return SIGN_IN_HANDLERS[account.provider]( user, account, profile, email, credentials ); }, async jwt({user, token, account}) { // If `user` and `account` are set … -
django, problem with the - contact - keyword
I am new to django and trying to create a contact page. Here is my urls.py in the app folder: urlpatterns = [ path("contacts", contact_view), ] and my views.py contact_view(request): return HttpResponse('<h1>Contact Page</h1>') Everything works fine when trying: http://127.0.0.1:8000/contacts I've noticed when I change contacts to contact as the following: urlpatterns = [ path("contact", contact_view), ] and then try http://127.0.0.1:8000/contact, it gives: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/contact/ Using the URLconf defined in config.urls, Django tried these URL patterns, in this order: 1. admin/ 2. 3. about 4. contact The current path, contact/, didn’t match any of these. I've tried restarting the server and the VSCode. Not working! Appreciate any help on this. Windows 11, VSCode, django 4.2.4 -
IntegrityError FOREIGN KEY constraint failed [In django project ]
enter image description here While adding user data in DB through a form I created I got this error integrity error at \add_emp and it says foreign key constraint failed I tried deleting dbsqlite3 files, migrations files, and pychache files but that did not work please tell me where I am wrong it's my first time getting this error. from django.db import models # Create your models here. class Department(models.Model): name = models.CharField(max_length=100,null=True) location = models.CharField(max_length=100) def __str__(self): return self.name class Role(models.Model): name = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Employee(models.Model): first_name = models.CharField(max_length=100, null=False) last_name = models.CharField(max_length=100,null=True) dept = models.ForeignKey(Department, on_delete=models.CASCADE) salary = models.IntegerField(default=0,null=True) bonus = models.IntegerField(default=0,null=True) role = models.ForeignKey(Role, on_delete=models.CASCADE) phone = models.IntegerField(default=0,null=True) hire_date = models.DateField(null=True) def __str__(self): return "%s %s %s" %(self.first_name, self.last_name, self.phone) -
Behave Django Testing - Behave testing only uses dev database instead of test database
How to properly set up behave-django so that it can use a test database loaded with data using factories? Please have a look to the code I have written. environment.py environment.py import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SampleDemo.settings') django.setup() from behave import fixture, use_fixture from django.test.runner import DiscoverRunner from django.test.testcases import TransactionTestCase, TestCase from src.core.models import User class BaseTestCase(TransactionTestCase): @classmethod def setUpClass(cls): User.objects.create_superuser(username='setuadmin', password='admin', email='setuadmin@admin.com') super(BaseTestCase, cls).setUpClass() @classmethod def tearDownClass(cls): User.objects.filter().delete() super(BaseTestCase, cls).tearDownClass() @fixture def django_test_case(context): context.test_case = BaseTestCase context.test_case.setUpClass() yield context.test_case.tearDownClass() del context.test_case def before_all(context): django.setup() context.test_runner = DiscoverRunner() context.test_runner.setup_test_environment() context.old_db_config = context.test_runner.setup_databases() yield context.test_runner.teardown_databases(context.old_db_config) context.test_runner.teardown_test_environment() def before_scenario(context, scenario): use_fixture(django_test_case, context) feature file Feature: Polish Grading CRUD Test CRUD methods of Polish-Grading Module REST API testing framework Background: Given I set REST API server url Scenario: User login with valid credentials Given I provide user authentication credentials And I make an http post call to "/user/login/" api Then I must get a response with status code 200 and a jSon object with token Scenario: fetch grading details Given I provide the params to fetch polish-grading details When I set the HEADER param request content type as "application/json". And I send HTTP GET request as "/polish/fetch-grading/" Then I receive the Valid … -
Django Post Office - How can I add a foreign key in the Email model that references the Client model?
I'm utilizing the django-post-office library in my Django project. I aim to link the library's existing Email model to my Client model, ensuring that while a single client can have multiple emails, each email can only be linked to one client. Is this feasible? Interestingly, ChatGPT provided a solution, but it mentioned parameters (create_models, model_class) that don't exist in the library therefore the code below doesn’t work. However, I'm curious if ChatGPT might have been hinting at an approach I am not aware. Suggestions how to solve it ? from post_office.models import Email as PostOfficeEmail class ClientEmail(PostOfficeEmail): client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='emails') from post_office import mail def send_client_email(client, subject, message): mail.send( recipients=[client.email], sender='your_sender_email@example.com', subject=subject, message=message, create_models=True, # This will create an Email model instance model_class=ClientEmail, # Use our extended model ) # Associate the email with the client email = ClientEmail.objects.last() email.client = client email.save() -
Django: calling .only() on my model causing infinite loop?
I am using .only to fetch the required fields from my model, it seems like my __init__ method causing a inifinite loop when calling only on this model, and this is my model: class PodcastEpisode(models.Model): audio_metadata = models.JSONField(null=True) featured_artists = models.ManyToManyField(to=User, related_name='featured_artists') podcast_series = models.ForeignKey(to=PodcastSeries, on_delete=models.CASCADE, null=False) published = models.BooleanField(default=False) published_at = models.DateTimeField(blank=True, null=True) _original_audios = None # To store current data _published = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # self._original_audios = self.audio_metadata # self._published = self.published When I commented these lines self._original_audios = self.audio_metadata and self._published = self.published, it doesn't cause inifinite loop. I am not sure how this is happening even if I have included audio_metadata in my .only() fields. This is my query PodcastEpisode.objects\ .filter(id__in=id_list).prefetch_related(*prefetches).only(*['id' 'audio_metadata']) Please suggest me how do I use .only() and where should I place these _original_audios and _published variables.