Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Maintaining a local set of migrations differing from upstream
I have written patches for a Django project that take forever to be integrated upstream (or may not even be). Due to this, I have local migrations that I need to maintain. However, due to the way the migration numbering system works, I have to update their numbers everytime upstream adds a new migrations, and that doesn't even work properly as it creates conflicts with the database state. I've been trying to move them to a separate app, but it doesn't seem to be possible to apply them to the original app then. How to properly maintain your own set of migrations? -
Django and multithreading
I have Django view: def func(): ... instance = ...create() func2(instance) instance.attr = attr etc... So func() creates an instance, calls func2() and keeps on working. def func2(instance): request = request(instance) wait response response.data.save() The result of function 1 and function 2 are in no way related. Function 2 is related to output/input operations. Function 2 must be called by function 1 and must not block the operation of function 1. In the current project version, func2 is called with celery. But I'm not sure that's the right way, and it's better to call func2 with another thread. def func(): ... instance = ...create() thread = threading.Thread(target=func2, args=instance) thread.run() instance.attr = attr etc... Am I right? Thanks a lot! -
How to Connect Multiple Clients to a Django Socket Server Across Different Platforms
We have created a socket server using Django and need to connect multiple clients to it. Our setup involves the server running on one platform and clients connecting from different platforms. We have a few specific requirements: The Django server should be opened for immediate connectivity. We need to ensure that client and server connectivity works seamlessly, even when the client and server are on different platforms. Our goal is to understand if we are on the right track with our current implementation. 1.Are we on the right track with our current implementation for handling multiple client connections on a Django socket server? 2.How can we ensure the server handles clients from different platforms efficiently? 3.Are there any improvements or best practices we should follow to enhance connectivity and performance? -
Checkboxes in Django and JS not working properly
I have a serious problem with checkboxes. I'm creating a ToDo style application and I want it to save the changes (item_done = False or True) when the checkbox is clicked. I have implemented a JS script to make everything come out "smoothly", I am using jQuery. Unfortunately the following error appears: when clicking on the first item in the list, everything works smoothly but when clicking on the second, the change happens in the first and vice versa when clicking on the first the change happens in the second. I can't to figure out what I am doing wrong. I have included the code below. HTML with Django, list of items in task: <div class="card-header bg-transparent" ><h3>To-do list</h3></div> <div class="text-start"> <br/> <ul class="list-group"> {% if list_items %} {% for item in list_items %} {% if item.item_done %} <li class="list-group-item"> <input class="form-check-input" type="checkbox" checked="checked" value="{{ item.id }}" id="un-check-box"> {{ item.title }} </li> {% else %} <li class="list-group-item"> <input class="form-check-input" type="checkbox" value="{{ item.id }}" id="check-box"> {{ item.title }} </li> {% endif %} {% endfor %} {% else %} <p class="text-center">the task list is empty</p> {% endif %} </ul> JS code: <script> // Check if checkbox pressed $(document).on('click', '#check-box', function(e){ e.preventDefault(); $.ajax({ … -
Errors not displaying in login form in Django
In my Django project, I use django.auth for authentication. I have two similar HTML templates for registration and login. The problem is that while displaying errors (e.g., passwords don't match, password too short) works for registration, it doesn't for logging in. For example, if I enter an incorrect username and password and click the submit button, errors won't show up, the page refreshes, the username remains in the input box, but the password box is empty. That's all. If I provide the correct credentials, it logs me in correctly. If I display the form using {{ form.as_p }}, errors work fine. Below are both forms: Registration: <form method="post"> {% csrf_token %} <!-- Username --> {% if form.username.errors %} <ul> {% for error in form.username.errors %} <li class="small-red-text">{{ error }}</li> {% endfor %} </ul> {% endif %} {{form.username|add_class:"form-control"|attr:"id:register-username-input"|attr:"placeholder:Username"}} <!-- Password 1 --> {% if form.password1.errors %} <ul> {% for error in form.password1.errors %} <li class="small-red-text">{{ error }}</li> {% endfor %} </ul> {% endif %} {{form.password1|add_class:"form-control"|attr:"placeholder:Password"}} <!-- Password 2 --> {% if form.password2.errors %} <ul> {% for error in form.password2.errors %} <li class="small-red-text">{{ error}}</li> {% endfor %} </ul> {% endif %} {{form.password2|add_class:"form-control"|attr:"id:register-password-input"|attr:"placeholder:Confirm password"}} <button class="small-blue-button" type="submit" name="register">Register</button> </form> Logging: <form id="login-form" method="post"> … -
Django partial template rendering not updating the page, but showing up in console
I have a django-based webpage I am working on. This page allows for clicking on a item in a table and the intention is to display subitems related to the item, without redrawing the whole page. Though my subtemplate is being seen by Django and acted upon, instead of updating the portion of the html in the page, the resulting html is being dumped in the console. Here are some code snippets: main.html contains, among many other things, the following positioned where I want the content: {% include '_subtemplate.html' %} _subtemplate contains: {% for subitem in subitems %} <tr> <td><a onclick='mySubItemClick("{{ subitem.date }}")'>{{ subitem.date }}</a></td> <td>{{ subitem.my_note }}</td> </tr> {% endfor %} views.py contains: def get_my_subitems(requests, site_id): subitems = # code to get a list of objects return render(request, '_subtemplate.html', { 'subitems': subitems }) urls.py contains a correct path entry in urlpatterns: path('myitems/mysubitems/<int:site_id>/', views.get_my_subitems, name='get_my_subitems'), I have a javascript file that contains a method which makes a working ajax call where 'path: /myitems/mysubitems/' + obj.site_id Instead of seeing my list of subitem content reload in the html page, when I open the browser console, I am seeing the correctly templated html there and not in the page. <tr> <td><a onclick='mySubItemClick("June … -
How to build a search function in react native app?
I have a react native app. And I have a search function. The problem I am facing is that the search function only works when the whole word has been entered in the textfield. So for example Edelhert works. But if a user types in: Ed - then nothing happens. And if a user waits for a second in the search textfield. Then this error pops up: VM270:1 Uncaught SyntaxError: Unexpected identifier 'Promise' So the search api looks: import { API_URL } from "@env"; import { retrieveToken } from "../../services/authentication/token"; export const fetchAnimalData = async (text) => { const token = await retrieveToken(); try { if (token) { const response = await fetch(`${API_URL}/api/animals/?name=${text}`, { method: "GET", headers: { Authorization: `Token ${token}`, Accept: "application/json", "Content-Type": "application/json", }, }); return await response.json(); } else { throw new Error(token); } } catch (error) { console.error("There was a problem with the fetch operation:", error); throw error; } }; and the search context: /* eslint-disable prettier/prettier */ import React, { createContext, useEffect, useState } from "react"; import { fetchAnimalData } from "./animal/animal.service"; export const SearchAnimalContext = createContext(); export const SearchAnimalContextProvider = ({ children }) => { const [searchAnimal, setSearchAnimal] = useState([]); const [results, setResults] = … -
I am currently learning from the meta backend course and I have front end knowledge , do suggest some knowledge and path that will help me
I am a beginner in backend development , I want to get some advice from some experts backend developers about the learning path , what should I learn , where to start , provide me some free resources from where I can learn. I have knowledge of front end . I am expecting some real ans that will help me -
Is there any way to export an existing Django model information into a visual form
I understand that I can create .dot files using django-extensions. I am also able to create SVGs from the .dot file using pygraphviz. However, the outputs are huge, ugly and difficult to navigate. Are there any tools that people can recommend that might include some form of filtering, auto layout etc. -
pywinrm CredSSP NTLM BadMechanismError(context_msg="Unable to negotiate common mechanism", base_error=last_err)
I am trying to debug strange behaviour when using the pywinrm. It cannot open WinRM connection because of BadMechanismError: SpnegoError (1): expected string or bytes-like object, got 'dict', Context: Unable to negotiate common mechanism I am using it in a docker and the same image behaves differently. Running the image on one server produces error message below, running on different server I am not able to figure out what can be different 2024-06-27T14:38:56+0000 DEBUG _credssp MainProcess-10 MainThread-139775582927656 _step_initiate : Starting CredSSP authentication phase 2024-06-27T14:38:56+0000 DEBUG _negotiate MainProcess-10 MainThread-139775582927656 step : SPNEGO step input: 2024-06-27T14:38:56+0000 DEBUG _negotiate MainProcess-10 MainThread-139775582927656 _rebuild_context_list : Attempting to create kerberos context when building SPNEGO mech list 2024-06-27T14:38:56+0000 DEBUG _negotiate MainProcess-10 MainThread-139775582927656 _rebuild_context_list : Failed to create context for SPNEGO protocol kerberos: Configuration file does not specify default realm -1765328160 2024-06-27T14:38:56+0000 DEBUG _negotiate MainProcess-10 MainThread-139775582927656 _rebuild_context_list : Attempting to create ntlm context when building SPNEGO mech list 2024-06-27T14:38:56+0000 DEBUG _negotiate MainProcess-10 MainThread-139775582927656 _rebuild_context_list : Failed to create context for SPNEGO protocol ntlm: expected string or bytes-like object, got 'dict' 2024-06-27T14:38:56+0000 ERROR exception_handler MainProcess-10 MainThread-139775582927656 process_exception : (500) Exception occurred: Received error status from the server: (2148074245) UNKOWN_STATUS 0x80090305 2024-06-27T14:38:56+0000 ERROR exception_handler MainProcess-10 MainThread-139775582927656 process_exception : Received error … -
Issue with Django admin form: Custom file upload field affecting unrelated form field
I'm currently working on a Django project where I've extended the admin form to allow for multiple file uploads. I am following this article. However, I'm encountering an issue where my custom file upload field seems to be affecting an unrelated form field (property_title). Specifically, after implementing the custom file upload field, the value of property_title is being changed to the name of the uploaded image. Here is simplified version of my setup: Models: from django.db import models class Property(models.Model): property_title = models.CharField(max_length=100) # Other fields class PropertyImage(models.Model): property = models.ForeignKey(Property, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to='property_images/') Admin.py: from django.contrib import admin from .models import Property, PropertyImage from .forms import PropertyAdminForm class PropertyImageInline(admin.TabularInline): model = PropertyImage extra = 1 @admin.register(Property) class PropertyAdmin(admin.ModelAdmin): inlines = [PropertyImageInline] Change_form.html: {% extends "admin/change_form.html" %} {% block inline_field_sets %} {% for inline_admin_formset in inline_admin_formsets %} {% include inline_admin_formset.opts.template %} {% endfor %} <fieldset class="module"> {% comment %} <label for="id_photos_multiple">Upload Multiple Photos:</label> {% endcomment %} <h2>Upload Photos</h2> <input name="photos_multiple" type="file" multiple accept="image/*" /> </fieldset> {% endblock %} How can I implement this setup so that I will be able to upload multiple images without effecting other fields of the form. This issue which I figure out is … -
Django Test Case Failing: Function Not Returning Expected Sum of Related Model Fields
I am working with Django 4.2.2 and I have a test case that is failing because a custom function is not returning the expected sum of related model fields. so this is my test: class UnitaImmobiliareModelTest(TestCase): def setUp(self): self.user = User.objects.create_user(username='UtenteTest', password='testing') self.studio = Studio.objects.create( nome_studio="Studio Test", utente_creatore_studio=self.user ) self.commessa = Commesse.objects.create( anno=timezone.now(), nome_commesse="Commessa Test", numero_commesse="0001", descrizione="Descrizione della commessa", somme_utilizzabili=10000, tipo_committente=True, utente_creatore=self.user, studio_associato=self.studio, utente_permesso=True ) self.preventivoCommessaFase = PreventivoCommessaFase.objects.create( codice="0001", nome="test", descrizione="testing", commessa=self.commessa, costi=2.00, ) self.fasiPrestazionali = FasiPrestazionali.objects.create( nome_fase="test001", costo=3, preventivi_commessa = self.preventivoCommessaFase ) self.unitaImmobiliare1 = UnitaImmobiliare.objects.create( codice="0002", descrizione="test", latitudine=2.2, longitudine=1.2, utente_creatore_unita=self.user, preventivi_fase=self.preventivoCommessaFase ) self.unitaImmobiliare2 = UnitaImmobiliare.objects.create( codice="0003", descrizione="test", latitudine=2.2, longitudine=1.2, utente_creatore_unita=self.user, preventivi_fase=self.preventivoCommessaFase ) def test_calcola_spesa_totale(self): expected_spesa_totale = Decimal('4.00') result = calcola_spesa_totale(self.preventivoCommessaFase) self.assertEqual(result, expected_spesa_totale) i am trying to test the func "calcola_spesa_totale" : print(f"QuerySetData: {computi}") print(computi[1].preventivi_fase.costi) totali_unita_immobiliari = ( computi.values("descrizione") .annotate(totale_costo=Sum(Cast("preventivi_fase__costi", FloatField()))) .order_by("descrizione") ) print(f"somma totale: {totali_unita_immobiliari}")#asd spesa_totale = sum( Decimal(item["totale_costo"] or 0) for item in totali_unita_immobiliari ) print(f"Spesa Totale Calcolata: {spesa_totale}") #asd return spesa_totale` ` problem is by the time i get inside this function, the error has already occured meaning that, the value of preventivi_fase.costi has already been set to 0.0 by my investigation this happens inside the Model PreventivoCommessaFase def totale_fasi this is the other model FasiPrestazionali containing … -
cannot import name 'AggsProxy' from 'elasticsearch_dsl.search'
my pip installs are elastic-transport==8.13.1 elasticsearch==8.14.0 elasticsearch-dsl==8.14.0 django-elasticsearch-dsl==8.0 django-elasticsearch-dsl-drf==0.22.5 services: elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:8.14.0 environment: - xpack.security.enabled=false - discovery.type=single-node ports: - "9200:9200" volumes: - elasticsearch-data:/usr/share/elasticsearch/data volumes: elasticsearch-data: -
Django web app was blocked due to MIME type (“text/html”) mismatch
I am trying to build a web-app with Django with a front-end made with Vue.js. Here is how my dir is organized - reco_system_app/urls.py reco_system_app/settings.py recommender/urls.py recommender/views.py vueapp/ static/ templates/ reco_system_app/urls.py is from django.contrib import admin from recommender.views import home from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('recommender.urls')), path('', home, name='home'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py has these two set STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] recommender/urls.py is from django.urls import path from . import views urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('movies/', views.get_random_movies, name='get_random_movies'), path('recommend/', views.get_recommendations, name='get_recommendations'), ] view.py is import random from django.shortcuts import render from django.views.generic import TemplateView from django.http import JsonResponse class IndexView(TemplateView): template_name = 'index.html' def home(request): return render(request, "index.html") def get_random_movies(request): # Simulate a list of movies sample_movies = ["The Shawshank Redemption", "The Godfather", "The Dark Knight", "Pulp Fiction", "The Lord of the Rings: The Return of the King"] # Return a random sample of 5 movies movies = random.sample(sample_movies, 3) return JsonResponse({"movies": movies}) def get_recommendations(request): # For simplicity, assume the movies are passed as a comma-separated string in the query parameter selected_movies = request.GET.get('movies', '') selected_movies_list = selected_movies.split(',') … -
(debug_toolbar.E001) The Django Debug Toolbar can't be used with tests
The complete error message is as below ?: (debug_toolbar.E001) The Django Debug Toolbar can't be used with tests HINT: Django changes the DEBUG setting to False when running tests. By default the Django Debug Toolbar is installed because DEBUG is set to True. For most cases, you need to avoid installing the toolbar when running tests. If you feel this check is in error, you can set `DEBUG_TOOLBAR_CONFIG['IS_RUNNING_TESTS'] = False` to bypass this check. How to recreate: Install django-debug-toolbar by running pip install django-debug-toolbar Run your test cases using python manage.py tests I could not find this question anywhere on StackOverflow. Hence, I'm posting this and answering it. -
Django failing to use its own UUID, tries to do a hex replace errors with new items added to model
This is happening on both my local and my prod solution, both are new Django projects and no data is transferred between them (new db every time). Whenever I try to make a new entry in one of my models, it throws a AttributeError 'int' object has no attribute 'replace' Initially I thought it was something wrong with my code that writes data into the db, but I found its happening when I try and enter something new via the admin panel. Tracing it back further it appears to be coming from the internal code trying to clean up the UUID but failing: hex = hex.replace('urn:', '').replace('uuid:', '') I'm pretty lost as to what to do next given this is internal Django code that's throwing a fit and I'm not giving it the UUID values, those are coming from my model which uses their recommended code: class Articles(models.Model): # Fields id = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False) title = models.CharField(max_length=256,blank=False,null=False,help_text="", verbose_name="Article Title") url = models.URLField(blank=False,null=False, help_text="", verbose_name="Article URL") image_url = models.CharField(max_length=512,blank=False,null=False,help_text="", verbose_name="Image Reference") site = models.ForeignKey(Sites, on_delete=models.CASCADE) published = models.DateField(null=True, blank=True, help_text="The date the article was published", verbose_name="Published Date") created = models.DateTimeField(auto_now_add=True,null=True, blank=True, help_text="The date the article was created in the site", verbose_name="Created … -
HI, I'M A FIRST TIME DJANGO USER
It's my first time using django. I have an error on running the server. the terminal says that django couldnt find my 'settings' module.What should i do? This is what blackbox.ai says "The error message indicates that Django is unable to find the settings module in your project. This is likely because the DJANGO_SETTINGS_MODULE environment variable is not set correctly." I tried my best but still can't solve the problem -
Python Django admin side request and approval
Behalf of gym management project I need to request trainer to get access to gym website so, when trainers requested with his personal and professional details then, the admin can view the details and approve or delete request. When it approved it automatically save to db . How will I do this in python Django I searched for a long, But i can't -
Social Login with Django Rest Framework and Dj-rest-auth
I have configured social login with Google with dj-rest-auth and Django rest framework. When I sign-up using normal the normal register view from dj-rest-auth, I can't login using the Gmail of same account. E.g I sign-up up normally using register with email: ifeanyinneji777@gmail.com. and then I tried logging in with Google with the same email. It says that a user with this email address already exists. Expecting to be logged in properly using Google. -
Django admin tabularinline similar queries
I'm developing an online store using Django. I have a main class Product class Product(models.Model): our_code = models.CharField('Наш артикул', max_length = 255, unique=True, blank=True, null=True) name = models.CharField('Наименование',max_length = 255, blank=True, null=True) full_name = models.CharField('Полное наименование',max_length = 255, blank=True, null=True) PRICE_TYPE_CHOICES = [ ('manual', 'Ручная установка'), ('rrc', 'РРЦ'), ('mrc', 'МРЦ'), ] CURRENCY_TYPE_CHOICES = [ ('rub', 'RUB (₽)'), ('usd', 'USD ($)'), ('eur', 'EUR (€)'), ('gbr', 'GBP (£)'), ] price_type = models.CharField('Тип цены',max_length=10, choices=PRICE_TYPE_CHOICES, default='manual') manual_price = models.DecimalField('Ручная цена',max_digits=20, decimal_places=2, blank=True, null=True) rrc_price = models.DecimalField('РРЦ', max_digits=20, decimal_places=2, blank=True, null=True) mrc_price = models.DecimalField('МРЦ', max_digits=20, decimal_places=2, blank=True, null=True) currency = models.CharField('Валюта',max_length=10, choices=CURRENCY_TYPE_CHOICES, default='rub') price_currency = models.DecimalField('Цена в валюте', max_digits=20, decimal_places=2, blank=True, null=True) text_short = models.TextField('Краткое описание', blank=True, null=True) text_full = models.TextField('Полное описание', blank=True, null=True) Associated with it is the ProductWith class, which stores similar products and is displayed in the Product class in the admin panel class ProductWith(models.Model): product = models.ForeignKey(Product, related_name='primary_product_with', default=None, on_delete=models.CASCADE, verbose_name='Товар') product_with = models.ForeignKey(Product, related_name='product_with_products_with', default=None, on_delete=models.CASCADE, verbose_name='Советуем купить') code admin.py class ProductWithAdmin(admin.TabularInline): model = ProductWith fk_name = 'product' extra = 0 raw_id_fields = ('product_with',) autocomplete_fields = ('product_with',) class ProductAdmin(admin.ModelAdmin): inlines = (ProductProviderAdmin, ProductImageAdmin, ProductAnalogAdmin, ProductColorAdmin, ProductWithAdmin,) search_fields = ['name', 'our_code'] autocomplete_fields = ["category", "manufacturer", "provider"] The problem is that … -
Gunicorn service stopping under supervisor with docker
I've using supervisor, nginx and gunicorn to deploy Django project with Docker. I'm running docker-compose up to build the project and nginx image. Going through other similar issues, it is recommended to use absolute path such as /home/ubuntu/... But since I'm using docker containers to run the project where I'm copying project in /app with COPY . /app/. I'm confused as to what write in directory in supervisor file. Below is my supervisor configuration. [supervisord] nodaemon=true [program:gunicorn] command=gunicorn trade_calls.wsgi:application --bind 0.0.0.0:8000 directory=/app user=root autostart=true autorestart=true stderr_logfile=/var/log/gunicorn.err.log stdout_logfile=/var/log/gunicorn.out.log [program:nginx] command=nginx -g "daemon off;" autostart=true autorestart=true stderr_logfile=/var/log/nginx.err.log stdout_logfile=/var/log/nginx.out.log The error I'm facing is docker-compose logs -f web web-1 | 2024-06-26 21:41:45,768 CRIT Supervisor is running as root. Privileges were not dropped because no user is specified in the config file. If you intend to run as root, you can set user=root in the config file to avoid this message. web-1 | 2024-06-26 21:41:45,771 INFO supervisord started with pid 1 web-1 | 2024-06-26 21:41:46,775 INFO spawned: 'gunicorn' with pid 7 web-1 | 2024-06-26 21:41:46,779 INFO spawned: 'nginx' with pid 8 web-1 | 2024-06-26 21:41:47,365 WARN exited: gunicorn (exit status 3; not expected) web-1 | 2024-06-26 21:41:48,368 INFO spawned: 'gunicorn' with pid 11 web-1 … -
Broken Process Pool: Processpool executor inside django app hosted on apache
I have a django application that I would like to host on my apache server. Use case of the application is to receive requests and performs compute intensive operations over a set of given inputs. To parallelise my computations I used future.ProcessPool executor in the core of the django app. Parallelisation in indispensable for my application. While the above setup works locally, I face BrokenProcessPool error especially when the app is hosted on the apache server. Tried few tricks in some related questions (here) but I have no clear idea what is happening or how to resolve it. Could someone please help me understand: Technically, what is the underlying issue in my setup? How do I resolve it without massively changing my existing framework(Django, Apache)? Can you provide me references for an ideal workflow used in some well known data-science or graphics web applications using Django and parallel computations. This could help me revise my current framework. Below is some relevant information views.py looks like import core.ray_trace def get_heatmap(request): list_of_inputs = request.POST.get('inputs') # parallel computation of list happens inside raytrace response_data = ray_trace(list_of_inputs) return JsonResponse(response_data, status=200) Apache config for my project WSGIDaemonProcess sp python-path=/home/ubuntu/_/spaceplanning python-home=/home/ubuntu/_/venv processes=3 threads=10 request-timeout=600 WSGIProcessGroup sp … -
How to serve static files for django-cms on DigitalOcean
I have deployed a django-cms app on DigitalOcean following the steps in this tutorial: https://www.digitalocean.com/community/tutorials/how-to-deploy-django-to-app-platform The app is up and running but static-files are not served. I created the additional static site refering to the same github repository and it is up and running too. settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_DIRS = [ BASE_DIR / "project_name" / "static", ] I did collect the static files with python manage.py collectstatic and the folder and files are present in the intended location. How do I "connect" the app on DigitalOcean to my static files? -
Django Rest Framework Api and seperate html css frontend
I make a django project where i made a model of product. i send this data through api in json form. In seprate html css js page i fetch the api and show all my data product. but i could not find the image solution to solve this issue. because url is passed by json but issue is that how we gave the path by frontennd where that image exists. i want to show that image on frontend that is placed at different place fron django project. what would be best approach or refer me some articles related to it. -
Django 'IntegerField' object has no attribute 'get_internal_type'
So guys i have been trying to use the ExpressionWrapper in django and get outputfield as a IntegerField(), I don't know where I am going wrong The imports # Imports from django.core from attr import fields from django.db import models from django.db.models import DecimalField, IntegerField, Avg,Subquery,OuterRef, Q, Sum, F, ExpressionWrapper from django.db.models.functions import ExtractYear from django.contrib.auth.models import User from django.forms import DateField, DecimalField, IntegerField from django.shortcuts import get_object_or_404 from django.utils import timezone # Imports froms apps from shop.models import CartItem, Order, OrderItem, Product, Review from wallets.models import Transaction, Wallet This is code part of a model method Profile.objects.filter( id__in = Wallet.objects.filter( id__in=purchases_made_for_on_store_products.values('wallet') ).values('user') ).values('dob').annotate( age = ExpressionWrapper(ExtractYear(dt.today()) - ExtractYear(F('dob')), output_field=IntegerField())) ) I was expecting the code to calculate the age of each of each user and store it temporarily in in a field called "age". this would allow me to annotate it and further used for filtering.