Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Websocket with Cloudflare proxy closes connection instantly with code 1006
What is the issue or error you’re encountering I have create a Django app which run on a uvicron server on and AWS EC2. The EC2 is attached to a load balancer which is then connected to cloudflare proxy. If I remove cloudflare proxy, websockets work fine, even with SSL/TLS enabled, https, etc. But as soon as I turn on cloudflare proxy (orange cloud), the websocket conneciton instantly close upon opeing. They give 1006 error code which means nothing. What steps have you taken to resolve the issue? I have looked at the logs, to see that the handshake is a successful. But when this reaches to the client, websocket disconnects, instanlty. app-be | INFO: ('172.18.0.7', 58718) - "WebSocket /ws/debug/" [accepted] app-be | INFO: connection open app-fe | 10.2.0.231 - - [31/Aug/2025:12:47:26 +0000] "GET /ws/debug/ HTTP/1.1" 101 0 "-" app-be | INFO: connection closed app-be | [django] [INFO] [2025-08-31 13:17:53,550] WebSocket disconnected: 1006 I have even sent a message just after connection, in the logs I can see a message has been sent, but client never receives it. I don’t know where do I go from here, I have: Websockets enabled on cloudflare I am sending a keep alive notification … -
Git is not making a conflict when I think it should be
I am learning how to deploy a django website and for that I have 2 copies of the code in 2 Git branches one for developing (master) and the other for deploying (deployment) with differint configuarations. I did some modification in master branch and want them to be availabe in deployment. I should have some conflicts because of the different configurations files like in settings.py there is debug=True in master and allowed hosts are empty, in the other hand it is False in deployment and allowed hosts are added. Git is not making any conflicts with these 2 lines so I am not able to choose which one I want when merging into deployment. side note: the modifications in git master branch that I want to bring to deployment should not do any conflicts. the conflicts I am waiting are just in already existed differences in the code (the purpose of having these 2 branches). -
what does shutil.rmtree(d, ignore_errors=True) do?
I was working with shutil module. My file structure looked like this projects/backend/--3-5 repos-- . In one of the repo's views.py I used for d in destDirs: shutil.rmtree(d, ignore_errors=True) destDirs = "projects/backend/repo1/static/file1 After that my whole file system got deleted. After running the API that had that code my whole file system got deleted. -
How to containerize a Django App properly?
I have sucessfully developed a Django App. However, i made some changes to the admin-panel and actually I can only successfully deploy the App in my tes-environment when I migrate the base-"makemgrations" and copy afterwards the changed migrations files for admin panel and so on and repeat the 'migrate' command afterwards. Reason is clear: in first migrate-command, there are no database fields to accept the changes i made. But how can I put this in a Docker-Containerized package for distributionwithout this issue? -
Django OneToOneField, Pyright: Cannot access attribute (reportAttributeAccessIssue)
I try to check my Django project with pyright. There is this OneToOneField, which pyright does not detect, when I use it: user.lala Error message of pyright: error: Cannot access attribute "lala" for class "User" Attribute "lala" is unknown (reportAttributeAccessIssue) # file lala/models.py class LaLaUser(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, related_name="lala" ) discount = models.PositiveSmallIntegerField( default=0, verbose_name="Discount (0 bis 100)", validators=[MinValueValidator(0), MaxValueValidator(100)], ) def __str__(self): return self.user.username The django-stubs are installed, and all other Django magic works fine with pyright. Version: Django 5.2, pyright 1.1.404. How to make pyright understand that OneToOneField? (ignoring that via a comment is not an answer) -
How can use jwt and allauth. and is combing the neccessary?
I. Have been try to combine both jwt and django allauth but i'm still considering that is not important I have read different dicumentation but i was not still statified please i need some advice And is my allauth email-verfication is showing the Ip address of the site how can i make it to the site name -
Problem with setting default file storage to boto for s3 integration?
The default storage does'nt change! There by not letting me add images to the aws bucket and coz of that it shows an access denied message when i open the image url but in reality it just added the image to my local system so there is nothing in that url!! I built an ecom website using django and now i want to integrate aws s3 for being able to add the images via the admin pannel and it being stored in the aws bucket! I tired changing the default storage in the settings.py and even tried using gpt and after all that when i check the default file storage it keeps showing my local storage! and when i add an image via the admin page it just creates a folder called products locally and add the image there! Please help me fix this!! -
Django doesn't release database connections for re-use, long after request has finished
My django app loads several pages (images) at once, e.g. to show a document, and queries the database mainly to check permissions. Django keeps the connections alive, but doesn't re-use them. At some point the maximum number of connections of postgresql is reached, and will never be 'unreached' because of this behavior. I've added CONN_MAX_AGE of 15 seconds and intermediate pgbouncer, but the behavior is the same, the connections stay open, even after 15". { "default": { "ENGINE": "django.db.backends.postgresql", "HOST": "pgbouncer","PORT": 6432,"NAME": "...", "USER": "...", "PASSWORD": "...", "CONN_MAX_AGE": 15, "CONN_HEALTH_CHECKS": true } } The settings point to a pgbouncer proxy in this case, but I also have this issue without pgbouncer. Here's what I see. I've loaded a couple of pages on the website, and they fill up pg_stat_activity. SELECT split_part(query, 'WHERE', 2) AS sql, COUNT(*) AS count FROM pg_stat_activity WHERE datname = '...' GROUP BY query sql count ... "page"."page_id" = 12 ... 1 ... "page"."page_id" = 65 ... 1 ... "page"."page_id" = 23 ... 1 ... "page"."page_id" = 78 ... 1 ... "page"."page_id" = 32 ... 1 ... many more rows ... ... These entries stay, with exactly the same page_id, for hours, eventhough the development console of … -
Django-Tenant-Users: IntegrityError on permissions_usertenantpermissions_profile_id_key when creating a tenant
I’m using Django with django-tenants and django-tenant-users to manage multi-tenant accounts. I’m having an issue when creating a new tenant: When I try to create a new user + its tenant through my view, I get the following error: django.db.utils.IntegrityError: ERROR: Duplicate key value breaks unique constraint 'permissions_usertenantpermissions_profile_id_key' DETAIL: Key '(profile_id)=(8)' already exists. I even cleared the table and tried but with all that the error is there Here is the code for my school_login view: def school_login(request): if request.method == 'POST': form = CreateSchoolForm(request.POST) if form.is_valid(): sigle = form.cleaned_data['sigle'] slug = form.cleaned_data['sigle'].lower() email = form.cleaned_data['email'] password = form.cleaned_data['password'] # Create the user user = SchoolUser.objects.create_user( email=email, password=password, ) user.role = 'director' user.is_verified = True user.save() # Create the tenant tenant, domain = provision_tenant( tenant_name=sigle, tenant_slug=slug, owner=user, is_superuser=True, is_staff=True, ) # Authenticate and login authenticated_user = authenticate(request, username=email, password=password) if authenticated_user: login(request, authenticated_user) tenant_domain = get_tenant_domain_model().objects.get(tenant=tenant).domain return HttpResponseRedirect(f"http://{tenant_domain}/") else: form = CreateSchoolForm() return render(request, 'school_login.html', {'form': form}) Here is the code of models.py in the shared app: class SchoolUser(UserProfile): ROLE_CHOICES = ( ('director', 'Directeur'), ('accountant', 'Comptable'), ) role = models.CharField(max_length=20, choices=ROLE_CHOICES, default='accountant') def is_director(self): return self.role == 'director' def is_accountant(self): return self.role == 'accountant' class School(TenantBase): name = models.CharField(max_length=100) # … -
My django app broke after windows reinstallation
Yesterday I reinstalled Windows and now my Django project’s Google login (using django-allauth v0.65.11) stopped working. I use a virtual environment and reinstalled the same dependencies (pip freeze matches exactly). Before the Windows reinstall, everything worked fine. Now, when I try to log in with Google, I get this error on the website: Third-Party Login Failure An error occurred while attempting to login via your third-party account. The server console only shows this: [28/Aug/2025 14:57:57] "GET /accounts/google/login/callback/?state=h7XieABcvxcuZgpX&code=4%2F0AVMBsJjAduD5uQ3tC334RqFwdAan0rK229B-qJzKmTizkmO68aNYOHyq26FIaYf_WwVYDA&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+openid&authuser=1&prompt=consent HTTP/1.1" 200 1152 No errors, no traceback, nothing. Even my custom adapter methods: class MySocialAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): print(">>> pre_social_login <<<") def populate_user(self, request, sociallogin, data): print(">>> populate_user <<<") are never called. What I’ve tried: Confirmed Google OAuth credentials in Google Cloud Console Checked that SOCIALACCOUNT_ADAPTER path in settings.py is correct Deleted and re-migrated the database Created a fresh Django project and copied code — issue persists Reinstalled Python (3.12) and all dependencies Settings (short): INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'tailwind', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'theme', 'django_browser_reload', 'django_ckeditor_5', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "django_browser_reload.middleware.BrowserReloadMiddleware", 'allauth.account.middleware.AccountMiddleware', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] SOCIALACCOUNT_ADAPTER = "core.adapters.MySocialAccountAdapter" SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': … -
Specify in which order to apply filters in django_filters.FilterSet
Within a django_filters.FilterSet: class SomeFilter(django_filters.FilterSet): model = SomeModel fields = { "is_archived": ("exact",), } include_ancestors = django_filters.BooleanFilter(method="include_ancestors_filter") def include_ancestors_filter(self, queryset, name, value): pass how can I specify that the filter field include_ancestors should be applied after all other filter fields (e.g. is_archived)? This is needed in my case because including the ancestors depends on the result set (i.e. depends on what children have been included based on all other filters). -
How to implement recurring payments in Django using QuickBooks Payments (card-on-file vs vault token)?
I am building a Django-based subscription system and integrating it with QuickBooks Payments. My goal: Allow a customer to enter their credit/debit card details once. Store their card in a secure way. Charge them automatically every month (like Stripe Subscriptions). What I’ve tried so far: I can successfully create a Vault Token using the QuickBooks Payments API when a customer enters their card. I am able to make a one-time charge using that token. The problem: The Vault Token seems to be one-time only (not reusable for future charges). I want to know the correct way to store a card-on-file for recurring billing. Do I need to use the QuickBooks Customer API to attach the card permanently? Or is there a way to reuse the Vault Token for recurring charges? Django 5.2 Celery for scheduling monthly tasks QuickBooks Payments API (sandbox) I currently store: qb_customer_id, vault_token, last4, expiry dateyour text def charge_recurring_payment(access_token, realm_id, user, amount): url = "https://sandbox.api.intuit.com/quickbooks/v4/payments/charges" headers = { "Authorization": f"Bearer {access_token}", "Accept": "application/json", "Content-Type": "application/json" } payload = { "amount": str(amount), "currency": "USD", "cardOnFile": { "value": user.qb_vault_token, # <--- works once, fails later "type": "TOKEN" } } resp = requests.post(url, json=payload, headers=headers) return resp.json() How do I … -
django tenants seeing data in all schemas
So I migrated my app to django tenants, in my local, I don't have any issues, I create a tenant and I don´t see the same data as public, but in the prod environment I see the data from public schema, I checked the database and the tables of the domain that I created appart from public is empty. settings.py # Application definition SHARED_APPS = [ 'django_tenants', 'tenant_manager', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', 'django.contrib.sites', 'widget_tweaks', "django_tables2", 'django_filters', 'bot', 'CCDC' ] TENANT_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', 'django.contrib.sites', 'bot', ] INSTALLED_APPS = SHARED_APPS + [ app for app in TENANT_APPS if app not in SHARED_APPS ] MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'tlgrmbot.urls' PUBLIC_SCHEMA_URLCONF = 'tlgrmbot.urls_public' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'tlgrmbot.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django_tenants.postgresql_backend', 'NAME': os.environ.get('DB_NAME_BOT'), 'USER': os.environ.get('DB_USER_BOT'), 'PASSWORD': os.environ.get('DB_PWD_BOT'), 'HOST': 'localhost', 'PORT': '5432', } } DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) TENANT_MODEL = "tenant_manager.Tenant" TENANT_DOMAIN_MODEL = "tenant_manager.Domain" SHOW_PUBLIC_IF_NO_TENANT_FOUND = True the schemas are public and doyangrlt even if … -
Issues with djangocms-text upgrade, configuration & custom settings not working in django app
I'm working on a project that uses django, djangocms, and djangocms-text-ckeditor. The project is old and desperately in need of updating, so i'm currently updating these major packages one at a time. Due to djangocms-text-ckeditor no longer being supported and not supporting the latest django or djangocms, I swapped it out with djangocms-text and followed the steps they recommended to migrate/update from ckeditor and the djangocms-text describes itself as ckeditors replacement for django. However, we had a lot of custom styles & css installed in the old text-ckeditor, and after initially getting djangocms-text to work with the base settings, I started working on adding in all of our custom styles and css, while also playing around with using the tiptap editor (default for text) or using ckeditor4, which comes with djangocms-text. It seems like I did get the styles to be recognized at some point and I know I was able to at least alter what styles were displayed in the dropdown, but now, after hours of trying, none of my configuration settings are taking effect at all, not even TEXT_INLINE_EDITING = False, which I know worked previously. I could really use some help here, the docs for these things … -
Custom Connection usage in graphene_django
I have a variation of the problem described here: Using DjangoFilterConnectionField with custom Connection in graphene_django The modified problem is as follows: Lets say I have a Django model class 'User', that has a field 'email_addrs' that is a comma-delimited string of email addresses: class User(models.Model): email_addrs = models.TextField(max_length=512, null=True, help_text="Comma-delimited string of email addresses") ...<other-fields>... And I have a UserNode(DjangoObjectType) built on top of that model, with a 'derived' field called 'count_email_addresses' with a resolver: class UserNode(DjangoObjectType): class Meta: model = User filter_fields = ('email_addrs', ) interfaces = (Node, ) connection = UserConnection count_email_addresses = graphene.Int() @static_method resolve_count_email_addresses(parent, info): # code to resolve the count of email addresses Note the UserConnection class (above, bound to the 'connection' Meta field) that I will describe next. The count_email_addesses field will return the number of email addresses for 'a user'. My requirement is to return the number of Users and the total number of email addresses across those users - which is an aggregation across the Users in my query. For that I am using the UserConnection class that is defined as: class UserConnection(Connection): class Meta: abstract = True count_users = graphene.Int() aggregate_count_email_addrs = graphene.Int() I need to write resolvers for 'count_users' … -
Django REST Framework: "No default throttle rate set for 'signup' scope" even though scope is defined
I’m trying to apply custom throttling for the signup endpoint in my Django REST Framework API. The goal is to allow only 5 signup attempts per hour for anonymous users. I created a SignupRateThrottle class that sets scope = "signup" and included it in DEFAULT_THROTTLE_CLASSES. I also added "signup": "5/hour" inside DEFAULT_THROTTLE_RATES in my settings.py. However, when I make a request to /api/v1/auth/signup/, I get this error: ImproperlyConfigured: No default throttle rate set for 'signup' scope Even though I already set the throttle rate for signup in my settings. I’ve double-checked that: The spelling of "signup" matches everywhere. Restarting the server doesn’t fix it. The error happens on a GET request, but I only intended to throttle POST requests. What I expected: Throttling should only apply to POST requests. After 5 signups in an hour, DRF should return 429 Too Many Requests. What happens instead: I get the ImproperlyConfigured error immediately. What I tried: Added "signup": "5/hour" in REST_FRAMEWORK["DEFAULT_THROTTLE_RATES"]. Restarted the server multiple times. Verified that scope = "signup" matches in both the throttle class and settings. Tried removing other custom throttles from DEFAULT_THROTTLE_CLASSES to isolate the issue -
why django migrate doesn't work even though I used make migration and it have not error
i create a new instance of Model an use makemigrations its work and this is my 0001_initial.py: class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='ProfileModel', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('avatar', models.ImageField(blank=True, default='accounts/avatars/default_avatar.jpg', upload_to='accounts/avatars/')), ('phone', phonenumber_field.modelfields.PhoneNumberField(blank=True, max_length=128, region=None)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)), ], ), ] when i use migrate Django cannot detect and apply changes to the database. Operations to perform: Apply all migrations: my_app Running migrations: No migrations to apply. i use python .\manage.py migrate accounts_app 0001_initial and its not work django say: No migration to Apply and when i use python .\manage.py showmigrations accounts_app There is a cross next to my migration file name. -
Django REST framework gives me csrf token missing when i am logged in for POST requests
i am making an API with django rest framework and django 5.2 when i send a POST request, if i be logged in it gives me an CSRF token missing error. but if i be logged out it gives me response with no error. here are my views for handling user creation and authentication: @api_view(['POST']) def signup_view(request): if not request.user.is_authenticated: serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({"detail": "The user is already logged in."}, status=status.HTTP_403_FORBIDDEN) @api_view(['POST']) def login_view(request): if not request.user.is_authenticated: user = authenticate(**request.data) print(request.POST) if not user: return Response({"detail": "User authentication failed."}, status=status.HTTP_400_BAD_REQUEST) login(request, user) return Response({"detail": "Login was succesful."}) return Response({"detail": "The user is already logged in."}, status=status.HTTP_403_FORBIDDEN) and here are my views for handling get and post method for the model: class NoteListView(APIView): def get(self, request): notes = Note.objects.filter(author=request.user) serializer = NoteSerializer(notes, many=True) data = [] for note in serializer.data: data.append({'title': note['title']}) return Response(data) def post(self, request): serializer = NoteSerializer(data=request.data) serializer.initial_data['author'] = request.user print("1") if serializer.is_valid(): print("2") serializer.save() print("3") return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) now i want to know what i have to do for fixing the csrf missing error in this situation. -
error: "get" is not a known attribute of "None" (reportOptionalMemberAccess)
I use PyRight to check my Django code. It complains about that class FooForm(ModelForm): def clean(self): cleaned_data = super().clean() start = cleaned_data.get("start_date") # <------- here error: "get" is not a known attribute of "None" (reportOptionalMemberAccess) I installed django-stubs. How to make PyRight aware that cleaned_data is a dictionary? Or is something wrong with my setup? -
Django 1.5.1: diagnose and fix Report
I've been handed a rather old Django installation to support, with the specific request to re-enable a report that used to go out every week or so, but stopped showing up a few months ago. Django v 1.5.1 Python 2.7.3 Ubuntu 12.04 (yikes) Problem is - I'm totally new to Django. I'm not sure where this report might be coming from, or how to troubleshoot it, or how to configure it. I was going to try the Admin pages; I finally was able to get my IP on the allow-list, and can bring up the login for that page, but I'm not sure what a valid user/PW is for this system. Where are the Django 'Admin' users kept? I'm able to access the MySQL DB backend itself - but the user-table for MySQL itself doesn't appear to be the source for the Django Admin users. So I would guess they are stored in a table in the Django eco-system... I'd like to just add a new user for myself, so I can log in and poke around in Admin. I have reviewed some Django documentation, but not seeming to find the answers to my questions, for either setting/administering users, nor … -
How to handle feature and permission-based authorization in Next.js without delaying initial render?
I’m building a multi-tenant SaaS application with Django Ninja as the backend and Next.js as the frontend. I’m running into a problem around handling RBAC permissions and org-level feature entitlements without causing bad UI behaviour. Current setup The app has a pre-defined set of permissions and features. Each organization can: Create their own RBAC roles for members. Define their own plans (feature bundles) for members. Hierarchy looks like: Platform → Org → Members. Problem For RBAC, I first tried fetching permissions/features from an API after login. But in Next.js, this caused a UX issue: On initial render, the UI displayed all components/features. Only after the API call resolved (or a manual refresh), the UI updated to hide restricted components. This led to a flicker effect where users briefly saw components they shouldn’t. To avoid this for RBAC, I moved the permissions into the JWT, so the frontend can instantly check them at page load. This works well, but I’m unsure if I should do the same for feature entitlements (since those are org-level and can change dynamically). Question Is it acceptable to also put feature entitlements in the JWT (and refresh the token on org/plan changes)? Or is there a … -
Patterns for testing web API permissions
I am working on a cookie cutter JSON web API. Think /items/<id> with your typical CRUD of delete, patch, get, and post. Recently, we started rolling out a new permissions model for the API, where certain operations are forbidden based on a combination of user and object properties. For example: We have two types of items - normal items and locked items, and we have two type of users - regular users and admin users. Users belong to a company. Regular users can mutate any normal item that belongs to their company, but not locked items Admin users can mutate any item (normal or locked) in their company. So the matrix for testing looks something like this: Test that regular users can do full CRUD on normal items in their company Test that regular users can get but not mutate locked items in their company Test that regular users can not do any CRUD on items not in their company Test that admin users can do full CRUD on normal items in their company Test that admin users can do full CRUD on locked items in their company Test that admin users can not do any CRUD on items not … -
Django 'join' tabels
I have 3 Tabels in Django class Transactions(models.Model): public_key = models.ForeignKey(Keys, on_delete=models.CASCADE) txid = models.CharField(max_length=30) timestamp = models.DateTimeField() hash = models.CharField(max_length=64) block = models.IntegerField() amount = models.IntegerField() saldo = models.IntegerField() fee = models.IntegerField() fiat_CHF = models.FloatField(default=0) fiat_USD = models.FloatField(default=0) fiat_EUR = models.FloatField(default=0) position = models.IntegerField(default=0) class Price(models.Model): date = models.DateTimeField() price = models.FloatField() fiat = models.ForeignKey(Currencies, on_delete=models.DO_NOTHING) class PriceTextBackup(models.Model): date = models.CharField(max_length=20) price = models.FloatField() fiat = models.ForeignKey(Currencies, on_delete=models.DO_NOTHING) This is from a Bitcoin App, the Transaction Table contains the exact time when transaction was mined. Now I want to load the stored bitcoin price for that day for example the transaction may have a timestamp of 2000-01-01 12:10:10 and the price 2000-01-01 so i want to join or link them. It doesn't have to be in database. I did something similar in a diffrent page to calculate the average price, i load both tables and 'join' them. In the end I want to display the transaction with a price. this price can come from price, pricetextbackup or be 0. Can this be achived and how? -
Django join where values not null
I have 3 Tabels in Django class Transactions(models.Model): public_key = models.ForeignKey(Keys, on_delete=models.CASCADE) txid = models.CharField(max_length=30) timestamp = models.DateTimeField() hash = models.CharField(max_length=64) block = models.IntegerField() amount = models.IntegerField() saldo = models.IntegerField() fee = models.IntegerField() fiat_CHF = models.FloatField(default=0) fiat_USD = models.FloatField(default=0) fiat_EUR = models.FloatField(default=0) position = models.IntegerField(default=0) class Price(models.Model): date = models.DateTimeField() price = models.FloatField() fiat = models.ForeignKey(Currencies, on_delete=models.DO_NOTHING) class PriceTextBackup(models.Model): date = models.CharField(max_length=20) price = models.FloatField() fiat = models.ForeignKey(Currencies, on_delete=models.DO_NOTHING) Now i want to 'join' transactions with price on the date, if it is null i want to check the text backup, if it is still null, i want it to be 0. Is that possible? and how? -
so many terminal messages when starting django runserver
when I start python manage.py runserver I get many messages similar to the following. File C:\Users\PC\OneDrive\Documents\DoseSaaS\DoseV3MasterSaaS\templates\admin\dose\tenant\change_list.html first seen with mtime 1754471094.0 to the point it fills the terminal window. How do I stop this? Could not find anything in the project and co-pilot could not help. checked settings.py and found nothing I could find. I looked for external services like watchdog but didn't find anything obvious.