Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integrate model representation with DRF Spectacular and Redoc, similar to the Pet Store Redocly example
I'm new to the developer sphere and the Python environment. As part of my apprenticeship, I'm working on a project to custom document a JS plugin. The project is set up with Django, drf-spectacular and redoc. I already have several views in place to expose the methods, events and properties of the plugin. I am currently having difficulty formatting two User and Addresses models with exactly the same behavior as the Pet and Order models present on the Pet Store API. Depending on the type chosen, the model changes. I've heard about Discriminator and PolymorphicSerializer but I'm a bit lost on what to do. I don't directly use the openapi schema. To generate the documentation, I run a script that will execute the npm command run bundle:standalone which will create the redoc.standalone.js that I then transfer to the Django static folder. Would anyone have a research lead or similar experience with the technologies used ? Thank you very much for your answers. Best regards. -
Styling Django CreateView Form
I want to design the form like option B Which shown in Image but not able to get the result My form looks like A. I am not using any Form or ModelForm just using CreateView. I also don't want to modify my Views or add any FormClass so please let me how can i get the Result. Here is my Model class InfluencerModel(models.Model): full_name = models.CharField(max_length=255, null=False, blank=False) email = models.EmailField(max_length=255, null=False, blank=False) contact_number = models.CharField(max_length=10, null=False, blank=False) instagram_id = models.CharField(max_length=50, null=False, blank=False) message = models.TextField(null=True, blank=True) visited_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email def get_absolute_url(self): return reverse("influencers") Views.py class InfluencersPageView(CreateView): model = InfluencerModel template_name = 'home/influencers.html' fields = ['full_name', 'email', 'contact_number', 'instagram_id', 'message'] def get_context_data(self, *args, **kwargs): context = super(InfluencersPageView, self).get_context_data(*args, **kwargs) return context Here is Template <form action="" role="form" class="php-email-form" method="post"> {% csrf_token %} <div class="row"> <div class="col-md-6 form-group"> {{ form.full_name.errors }} {{form.full_name|as_crispy_field}} </div> <div class="col-md-6 form-group mt-3 mt-md-0"> {{ form.email.errors }} {{form.email|as_crispy_field}} </div> <div class="form-group col-md-6"> {{ form.contact_number.errors }} {{form.contact_number|as_crispy_field}} </div> <div class="form-group col-md-6"> {{ form.instagram_id.errors }} {{form.instagram_id|as_crispy_field}} </div> </div> <div class="form-group mt-3" rows="7"> {{ form.message.errors }} {{form.message|as_crispy_field}} </div> <div class="text-center"> <button type="submit" class="btn btn-outline-secondary" style="background-color:#FF512F; color: white">Send Message</button> </div> </form> -
Browser doesn't find images from HTML when running on local host
I am developing my site and running on the local host now on windows computer. I want to set a background image for the page but when I run the server it throughs a message that the image is not found. The image is located in the same directory where the html is. This is a really simple thing but I am straggling with it from early morning. Looked in all the forums but nothing helped so far. I tried changing the file path as relative/absolute. But no result. No mistake in the file name or path. body { background-image: url("background.jpg") } -
CSRF token from the 'X-Csrftoken' HTTP header incorrect
I'm making a web application (a SPA, to be specific) with a separate frontend (React) and backend (DRF). It uses session authentication, but the CSRF token isn't correct for some reason, and I'm having a hard time figuring out why, specifically on the logout route of my application. Here's how I'm getting and sending the token: fetch(APIURL + "/api/csrf-token/") .then((response) => { return response.json(); }) .then((json_response) => { const XCSRFToken = json_response["X-CSRFToken"]; const logout_response = fetch(APIURL + "/api/logout/", { headers: { "Content-Type": "application/json", "X-CSRFToken": XCSRFToken, }, credentials: "include", method: "POST", }) // then do stuff But this yields the following error: CSRF Failed: CSRF token from the 'X-Csrftoken' HTTP header incorrect. I'm not sure where I'm going wrong here because I'm not sure how the CSRF token can be wrong. Before I give the rest of the code, there's one other thing that I'm confused about. When I log in, an HTTP only cookie called csrftoken is passed to my browser; should I be doing anything with that? Here's my views for getting the CSRF token and logging out. @api_view(["GET"]) def csrf_token(request): response = Response( {"detail": "CSRF cookie set", "X-CSRFToken": get_token(request)} ) return response @api_view(["POST"]) def logout_user(request): logout(request) If there's … -
Django Speed Up Aggregates
I am using Django as Analytics Dashboard where I fetch the Orders data from Takealot Seller API and then store each and every order in SalesModel. In a month, I get around 100000 orders and when I try to aggregate them using following code month = 1 year = 2024 SalesModel.objects.filter(account=user.pk, store=store.pk, order_date__year=year, order_date__month=month).aggregate(Sum("selling_price"))["selling_price__sum"] selling_price is a IntegerField while order_date is DatetimeField. and there are 10 more KPIs similar to it and Product Selling Trends (which are calculated on the go) too. trendData = SalesModel.objects.filter(account=user.pk, store=store.pk, order_date__year=year, order_date__month=month).values("order_date__year","order_date__month","order_date__day").order_by("order_date__year","order_date__month","order_date__day").annotate(total=Sum('selling_price'),total_units=Sum("quantity")) It takes solid 2-3 seconds, how can I speed this up? I am already using the cache which saves the data for 5 minutes. Should I have a separate Model where I add KPIs or what should I do? Want to speed it up. -
In my Website add-to-cart is not(bagicon) not changing its value
I created an add to cart function for my ecommerce website In my index.html: <button class="action-btn"> <ion-icon name="bag-handle-outline"></ion-icon> <span class="count cart-items-count">{{request.session.cart_data_obj|length}}</span> </button> In Image1 you can see that I created a bagicon and when I am clicking add to cart function it is changing Span value (0 to 1) but when I am clicking add-to-cart for another product it is not changing it's value from (1 to 2) In my function.js: $("#add-to-cart-btn").on("click",function(){ let quantity=$("#product-quantity").val() let product_title=$(".product-title").val() let product_id=$(".product-id").val() let product_price = $("#current-product-price").text() let this_val=$(this) console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("Title:", product_title); console.log("Price:", product_price); console.log("Current Element:", this_val); $.ajax({ url: '/add-to-cart', data: { 'id': product_id, 'qty': quantity, 'title': product_title, 'price': product_price }, dataType: 'json', beforeSend: function(){ console.log("Adding products to cart"); }, success: function(response){ this_val.html("Item added to cart") console.log("Added products to cart"); $(".cart-items-count").text(response.totalcartitems) } }) }) I also created a view for this So, in views.py def add_to_cart(request): cart_product={} cart_product[str(request.GET['id'])]={ 'title': request.GET['title'], 'qty': request.GET['qty'], 'price': request.GET['price'], } if 'cart_data_obj' is request.session: if str(request.GET['id']) in request.session['cart_data_obj']: cart_data= request.session['cart_data_obj'] cart_data[str(request.GET['id'])]['qty']=int(cart_product[str(request.GET['id'])]['qty']) cart_data.update(cart_data) request.session['cart_data_obj']=cart_data else: cart_data=request.session['cart_data_obj'] cart_data.update(cart_product) request.session['cart_data_obj']=cart_data else: request.session['cart_data_obj']=cart_product return JsonResponse({"data":request.session['cart_data_obj'],'totalcartitems': len(request.session['cart_data_obj'])}) Please help me out with this!!! -
How write Django model query to get product list with product available in wishlist or not?
models.py models.py class Product(models.Model): code = models.CharField(max_length=50, default=None, null=True, blank=True, unique=True) name = models.CharField(max_length=100) category_id = models.ForeignKey(category, on_delete=models.CASCADE) size_id = models.ForeignKey(size, on_delete=models.CASCADE) cost = models.IntegerField() tax_id = models.ForeignKey(Tax, on_delete=models.CASCADE) price = models.IntegerField() class wishlist(models.Model): product_id = models.ForeignKey(Product, on_delete=models.CASCADE, error_messages = {'unique': 'This Product is already in exist',}) user_id = models.ForeignKey(Account, on_delete=models.CASCADE) create_at = models.DateTimeField(auto_now_add=True) I'm trying to fetch all product like product.objects.all() with check particular product available on cart and wishlist or not -
How do I render snippets that represent ui components in pages on Wagtail CMS?
I am new to wagtail and i'm working on a project to build a cms. The cms will have some ui components like NavBars and cards that i am making throught snippets, so that i can reuse them in diferent pages (or even on the same page). My question is what's the best aproach to render this items? I thought of using templatetags, but i am not complete sure if thats a good idea. What do you think its a nice and clean way of doing this? -
In add to cart Span is not working properly
I Created a add to cart function for my website but in the website span is not working properly . My problem is that: You can see in the marked portion of the image if i clicked on add to cart button it is changing "0-1" but when I am clicking on add to cart button of an another product it is not changing from "1-2" So, In product-detail.html: <button class="action-btn"> <ion-icon name="bag-handle-outline"></ion-icon> <span class="count cart-items-count">{{request.session.cart_data_obj|length}}</span> </button> In js file: $("#add-to-cart-btn").on("click",function(){ let quantity=$("#product-quantity").val() let product_title=$(".product-title").val() let product_id=$(".product-id").val() let product_price = $("#current-product-price").text() let this_val=$(this) console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("Title:", product_title); console.log("Price:", product_price); console.log("Current Element:", this_val); $.ajax({ url: '/add-to-cart', data: { 'id': product_id, 'qty': quantity, 'title': product_title, 'price': product_price }, dataType: 'json', beforeSend: function(){ console.log("Adding products to cart"); }, success: function(response){ this_val.html("Item added to cart") console.log("Added products to cart"); $(".cart-items-count").text(response.totalcartitems) } }) }) In Views.py: def add_to_cart(request): cart_product={} cart_product[str(request.GET['id'])]={ 'title': request.GET['title'], 'qty': request.GET['qty'], 'price': request.GET['price'], } if 'cart_data_obj' is request.session: if str(request.GET['id']) in request.session['cart_data_obj']: cart_data= request.session['cart_data_obj'] cart_data[str(request.GET['id'])]['qty']=int(cart_product[str(request.GET['id'])]['qty']) cart_data.update(cart_data) request.session['cart_data_obj']=cart_data else: cart_data=request.session['cart_data_obj'] cart_data.update(cart_product) request.session['cart_data_obj']=cart_data else: request.session['cart_data_obj']=cart_product return JsonResponse({"data":request.session['cart_data_obj'],'totalcartitems': len(request.session['cart_data_obj'])}) So please help me out with this problem and I think that the probelm is in views because js file is working properly... In … -
Insert only to specific fields in formModel in django
I have a django model and its corresponding form to insert into and read value from a table with three columns in database. My requirement is I only need to insert in to say two column using form, leaving the third column which is a date field. But I have a requirement to read all three column to display it in html in later time. When I use exclude in the form it works good for the html part but when trying to save the form using form.save(), it tries to insert null in the the third column and raise error. Can anybody please help me to omit the third column completely while saving the form. Class sales(models.Model) product_name = models.CharField(max_length=500) quantity=models.FloatField() sale_date=models.DateField() -
django.core.exceptions.SynchronousOnlyOperation You cannot call this from an async context - use a thread or sync_to_async
I am using Django channels to implemented web sockets I wants to get database quries using ORM inside consumers.py look at my code import json from channels.generic.websocket import AsyncWebsocketConsumer from .models import Game from accounts.models import CustomUser as User from channels.db import database_sync_to_async `class CameraStreamConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): print("initializing") self.counter = 0 super().__init__(*args, **kwargs) async def connect(self): await self.accept() print("accepted connection") async def disconnect(self, close_code): pass print("disconect connection") async def receive(self, text_data=None,): print(" iam getting data online") data = json.loads(text_data) if data.get('type') == 'started': await self.handle_game_started(data) async def get_game(self, game_id): game_obj = await database_sync_to_async(Game.objects.get)(id=game_id) return game_obj async def get_user(self, user_id): user_obj = await database_sync_to_async(User.objects.get)(id=user_id) return user_obj async def handle_game_started(self, data): game_id = data.get('game_id') user_id = data.get('user_id') game_obj = await self.get_game(game_id) user_obj = await self.get_user(user_id) if game_obj and user_obj: game_creator = game_obj.creator if game_creator == user_obj: print("user is creator") await self.send(text_data=json.dumps({'message': f'Game {game_id} Started'})) ` and i am getting error django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. I try also with from asgiref.sync import sync_to_async but still getting same -
Django - Wants to restrict access to all of them to only logged-in users and I already have 100's of functions, is their anyway to add it directly?
In Python-Django views.py file I have 100's of functions and I want to restrict access to all of them to only logged-in users. I'm aware that I can add "@login_required(login_url='/admin/login/')" above every function and I works well. But as there are lots of function then adding it can be quite cumbersome. So, is there any way to achieve this without manually adding it to each and every function. Helps are highly appreciated. @login_required(login_url='/member/login/') def dashboard(request): id = request.user.id result = User.objects.get(pk=id) context={'result' : result} return render(request, 'member/dashboard.html', context) I want to restrict access to all of them to only logged-in users. -
I have a problem with static files in django
I cant refrence to contexts in js HTML {% load static%} {%block content%} <div id="backSign" , style="display: none;">go to lesions</div> <ol id="list"></ol> {% endblock content%} {% block extrajs %} <script src="{% static 'assets/js/idioms.js'%}"></script> {% endblock extrajs %} JS const Data = '{{ data|escapejs }}' console.log(Data) output : "{{ data|escapejs }}" when i put js in script tag it works but when i refrence the place its return this : {{ data|escapejs }} -
How to add m2m field, while iterating for copy objs
for a in Company.objects.all(): a.uuid=None a.save() a.users.add(*User.objects.all()) The goal of the code is duplicate Company and add all Users to it. It doesn't work, i need to save it first and iterate again to add the users. How can i add while iterating this object? I needed to save it first and iterate again to add the users. How can i add while iterating this object and duplicating it? -
Strategy to make django models with lots of memberfunctions more manageable?
I have a huge model because of its many member functions. I would like to organize the functions into separate classes according to their purpose, so everything is a bit more organized. Using OneToOneField is not a good option for me, because my app heavily relies on query caching (with cacheops). And I noticed that getting the latest version of a data object (from db) may be attached to a an outdated OneToOneField (from cache). Also, the number of data members is not a problem, only the number of member functions. So I would prefer to use just one data model. For example, I could do it this way: # models.py class MyModel(models.Model): # members # separate member functions class CustomModelFunctions: @staticmethod def some_function(my_model_instance): # logic # call the function on the my_model obj # instead of calling my_model.some_function() CustomModelFunctions.some_function(my_model) This works, but the problem is that these functions can not be used in django templates, since the my_model argument can not be passed. For example, I don't see how I could replace the following template code: {% if my_model.some_function %} Does anyone know a workaround for this? Or a different approach to organize models with a lot of member … -
How to make Django custom user restrict middleware?
urls.py path('panel/', include('panel.urls')), path('', include('base.urls')), non superadmin user restrict to access panel.urls superadmin user allowed panel.urls middllware.py # panel/middleware.py from django.shortcuts import redirect from django.urls import reverse class AdminRestrictMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.path.startswith('/panel/'): if request.user.is_authenticated: if not request.user.is_superuser: # If the user is not an admin, redirect them to a restricted page return redirect(reverse('restricted_access')) else: # If the user is not logged in, redirect them to the login page return redirect(reverse('login')) response = self.get_response(request) return response -
Django data getting saved in wrong model Why its saving the Model B,C data in model A
I have 3 django models CustomerDetail CarrierForm InfluencerModel When i am trying to save data in CarrierForm or InfluencerModel through different different page's forms its getting saved in model CustomerDetail Why its happening tell me what i am doing wrong? Here is Model class CustomerDetail(models.Model): full_name = models.CharField(max_length=255, null=False, blank=False) email = models.EmailField(max_length=255, null=False, blank=False) contact_number = models.CharField(max_length=10, null=False, blank=False) message = models.TextField(null=False, blank=False) visited_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email class CarrierForm(models.Model): full_name = models.CharField(max_length=255, null=False, blank=False) email = models.EmailField(max_length=255, null=False, blank=False) contact_number = models.CharField(max_length=10, null=False, blank=False) upload_resume = models.FileField(null=False, blank=False) message = models.TextField(null=True, blank=True) visited_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email class InfluencerModel(models.Model): full_name = models.CharField(max_length=255, null=False, blank=False) email = models.EmailField(max_length=255, null=False, blank=False) contact_number = models.CharField(max_length=10, null=False, blank=False) instagram_id = models.CharField(max_length=50, null=False, blank=False) message = models.TextField(null=True, blank=True) visited_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email Here is Views class HomeView(CreateView): success_url = reverse_lazy('home') model = CustomerDetail template_name = 'home/home.html' fields = ['full_name', 'email', 'contact_number', 'message'] def get_context_data(self, *args, **kwargs): context = super(HomeView, self).get_context_data(*args, **kwargs) context['files'] = HomeVideoAndImage.objects.all() context['galleryImages'] = HomeGallery.objects.all() context['reviewImages'] = Review.objects.all() return context class CarrierFormView(CreateView): model = CarrierForm template_name = 'home/carrier.html' fields = ['full_name', 'email', 'contact_number', 'upload_resume', 'message'] def get_context_data(self, *args, **kwargs): context = super(CarrierFormView, self).get_context_data(*args, **kwargs) … -
django two factor OTP in DRF
I want to protect one route in a project on DRF, but there are features, an example of implementation that I have not found on the Internet. The structure of logic is like this bellow Implement Two-Factor Authentication (2FA): Integrate a third-party service like Google Authenticator for generating verification codes. When a user tries to access the sensitive route, prompt them to enter a verification code along with their credentials. Verify the entered code with the code generated by the Google Authenticator or similar service. Email Verification: Maintain a list of email addresses that are allowed to access the sensitive route. Compare the email address of the authenticated user (request.user.email) with the list of allowed email addresses. If the user's email is in the allowed list, send a verification code to their email address. Prompt the user to enter the verification code received via email. Verify the entered code against the code sent to the user's email. Granting Access: If the user successfully completes both steps of authentication (2FA and email verification), grant them access to the sensitive route. Otherwise, deny access to the route. If anyone has encountered a similar implementation, please give me some direction -
connection failed: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432?
i am getting an error connecting to sql cloud during deployment to google cloud, in my sql cloud, IP public is 34.66.xx.xxx enter image description here but when I run code ./cloud-sql-proxy <connection_name> then feedback: 2024/03/05 22:53:02 Authorizing with Application Default Credentials 2024/03/05 22:53:03 [django-ecommerce-416314:us-central1:django-ecommerce-instance] Listening on 127.0.0.1:5432 2024/03/05 22:53:03 The proxy has started successfully and is ready for new connections! in my setting code django setting, I config database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'shopeedb', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': '34.66.xx.xxx', 'PORT': '5432', } } more detail: I can run server on UI server but when LOGIN, REGISTER,... related with DB it not active. What need I do now? Thanks! I tried change config DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'shopeedb', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': '127.0.0.1', 'PORT': '5432', } } results returned: enter image description here but when I run with config DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'shopeedb', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': '34.66.xx.xxx', 'PORT': '5432', } } results returned: 502 bad gate way Nginx -
Mypy with Django: type[MyModel] has no attribute "objects" [attr-defined]
After coding my Django model and adding a method which uses the "objects" manager, Mypy continues to show the error (command: "mypy ."): models.py:168: error: "type[MyModel]" has no attribute "objects" [attr-defined] How to solve that? -
Backend vs Frontend approach for upload of large files to remote storage
I am creating a software involving content delivery. It involves upload of large video files(100GB+). I understand that in general for file upload you can use the input element of html and upload it to the backend and from there you upload it to your storage. But this involves 2 uploads for 1 file and involves loading your large file into in-memory database in your backend. Im wondering if one could save some bandwidth and time, space and computation by somehow directly uploading from the frontend. What is the industry standard for dealing such a scenario? I've seen ways to upload large files from backend using multipart uploads using AWS sdk, but so far, I couldn't find a way to directly upload using HTML + JavaScript from the frontend itself(without loading the file into the in-memory database). I am using Django for backend, Angular for frontend and AWS s3 for storage. -
How to resolve a "DuplicateColumn" error when running Django migrations?
I'm encountering an issue while running migrations in my Django project. Here's the error message I'm receiving: psycopg2.errors.DuplicateColumn: column "order_address" of relation "orders_order" already exists This error seems to be related to the migrations process. I have checked my migration files and ensured that I'm not explicitly adding the "order_address" column multiple times. However, the error persists. What could be causing this error, and how can I resolve it? -
Not printing required data from json available data
[This is the source code. Here I iterate through a bunch of json entries and try to print only a few.] (https://i.stack.imgur.com/KUlfj.png) the last few empty columns are where I tried to print some specific data. It isn't printing it at all. The entries are supposed to be printed on a html page. I had tried to iterate through 'output' which had 2 json entries. I wish to print only a few specific values from each json entry but when i specified and ran the django webapp, it didn't print anything. -
csrf token is showing as text in the browser
enter image description herei am very new to django. i am trying to create a login form in django but when i write the csrf_token line after the tag it is showing in the browser view. everything is very confusing for me i don't know what to do. the tutorial that i watch on youtube only pass the csrf_token but don't say anything much. {% csrf_token %} Email Password Sign In Change Password this is a very simple form that i styled using tailwindcss and the csrf token is being shown. also my app has other errors. it does not run on the development server -
Error creating a closure table in Django: 'ForeignKey' object has no attribute 'column'
I have a Jobs model and need a closure table job_hierarchies schema looks like below Table job_hierarchies { account_id int [not null] ancestor int [not null, ref: > jobs.id] descendant int [not null, ref: > jobs.id] level int [not null] } I tried creating model & migration for JobHierarchy as below Model # api/models/job_hierarchy.py from django.db import models from .base import BaseModel from api.models import Job class JobHierarchy(BaseModel): account_id = models.IntegerField(null=False) ancestor = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='ancestor_jobs', db_column='ancestor_id') descendant = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='descendant_jobs', db_column='descendant_id') level = models.IntegerField(null=False) class Meta: db_table = 'job_hierarchies' Migration looks like below # Generated by Django 5.0.2 on 2024-03-08 04:28 from django.db import migrations, models def add_foreign_keys(apps, schema_editor): JobHierarchy = apps.get_model('api', 'JobHierarchy') Job = apps.get_model('api', 'Job') schema_editor.add_field( JobHierarchy, models.ForeignKey(Job, on_delete=models.CASCADE, related_name='ancestor_jobs', db_column='ancestor_id'), ) schema_editor.add_field( JobHierarchy, models.ForeignKey(Job, on_delete=models.CASCADE, related_name='descendant_jobs', db_column='descendant_id'), ) class Migration(migrations.Migration): dependencies = [ ('api', '0002_create_jobs'), ] operations = [ migrations.CreateModel( name='JobHierarchy', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('account_id', models.IntegerField()), ('level', models.IntegerField()), ], options={ 'db_table': 'job_hierarchies', }, ), migrations.RunPython(add_foreign_keys), ] When I run make migrations, I get below error File "/app/api/migrations/0009_create_job_hierarchies.py", line 8, in add_foreign_keys schema_editor.add_field( File "/usr/local/lib/python3.12/site-packages/django/db/backends/base/schema.py", line 730, in add_field "name": self._fk_constraint_name(model, field, constraint_suffix), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/db/backends/base/schema.py", line 1708, in _fk_constraint_name [field.column], ^^^^^^^^^^^^ AttributeError: …