Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Real time data not display it return an error message: {"error": "'QuerySet' object has no attribute 'body'"}
I like to implement real time data display in django app using Ajax, i want to enable user to be able to see what they are writing in real time, to do this, i'm using django JsonResponse, using the below method: def get_real_time_data(request): if request.method == 'POST': body = request.POST.get('body') try: question = Question.objects.filter(body=body) if question is not None: content = question.body response_data = { 'content': content } return JsonResponse(response_data) else: return JsonResponse({'error': 'No content found for the given body'}, status=404) except Exception as e: return JsonResponse({'error': str(e)}, status=500) else: return JsonResponse({'error': 'Invalid request method'}, status=400) Using the above method, it's means, every time, a user started writing something in the form, the data will be displayed in real time, but I don't know why the data does not display, instead, it return an error message in the browser console: Failed to load resource: the server responded with a status of 500 (Internal Server Error) question/:89 {"error": "'QuerySet' object has no attribute 'body'"} error @ question/:89 :8000/get-real-time-data/:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error) question/:89 {"error": "'QuerySet' object has no attribute 'body'"} error @ question/:89 jquery.min.js:2 POST http://127.0.0.1:8000/get-real-time-data/ 500 (Internal Server Error) … -
I am getting a console.log error in my django react application with CORS_ALLOWED_ORIGINS
According to the docs I have everything set up correctly but I am still getting an error. This is the error message from console.log() Access to fetch at 'http://127.0.0.1:8000/api/wells' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. This is the code from settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'wells', 'core', ] CORS_ALLOWED_ORIGINS = ['http://localhost:3000'] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] According to the docs, this should work. So, I am not sure how to fix the error. -
SQLALCHEMY cursor and execute AttributeError
I'm currently using sqlalchemy 2.0.29 in django with postgres sql and while updating an entry i encountered AttributeError regarding cursor and execute. try: qry = "UPDATE fhc_imp_glidepath_initiatives SET canceller = 'tan.gt.1', end_date = '05/04/2024 10:08:03' WHERE uid = '2'" conn = sa.create_engine(f'postgresql://{user}:{pwd}@{srv}:{port}/{db}') cursor = conn.cursor() cursor.execute(qry) conn.commit() return True except Exception as e: print(e) return False What will be the solution or proper query to fix this? Thank you in advance. Expecting to fix the AttributeError regarding cursor and execute when using sqlalchemy 2.0.29 and knowing what's the correct syntax to use in this type of situation. -
issue in Django 5.0.2 and django_rest_framework
hi guys i have issue with reading sql data from postgresql with django. i created my model with manage.py inspectdb command from existing database. my model: from django.db import models class Regions(models.Model): code = models.CharField(unique=True, max_length=4) capital = models.CharField(max_length=10) name = models.TextField(unique=True) class Meta: managed = False db_table = "regions" My serializer: from rest_framework import serializers class RegionsSerializer(serializers.ModelSerializer): class Meta: model = "france.models.Regions" fields = "__all__" my viewset: from rest_framework import viewsets from rest_framework.response import Response from .models import Regions from .serializers import RegionsSerializer class RegionsView(viewsets.ViewSet): def list(self, request): regions = Regions.objects.all() serializer = RegionsSerializer(regions, many=True) return Response(serializer.data) and error i get: AttributeError at /regions/ 'str' object has no attribute '_meta' Request Method: GET Request URL: http://127.0.0.1:1000/regions/ Django Version: 5.0.4 Exception Type: AttributeError Exception Value: 'str' object has no attribute '_meta' Exception Location: C:\Projects\play_ground\python\django_one\venv\Lib\site-packages\rest_framework\utils\model_meta.py, line 35, in get_field_info Raised during: france.views.RegionsView Python Executable: C:\Projects\play_ground\python\django_one\venv\Scripts\python.exe Python Version: 3.12.2 Python Path: ['C:\\Projects\\play_ground\\python\\django_one', 'C:\\Users\\safkh\\AppData\\Local\\Programs\\Python\\Python312\\python312.zip', 'C:\\Users\\safkh\\AppData\\Local\\Programs\\Python\\Python312\\DLLs', 'C:\\Users\\safkh\\AppData\\Local\\Programs\\Python\\Python312\\Lib', 'C:\\Users\\safkh\\AppData\\Local\\Programs\\Python\\Python312', 'C:\\Projects\\play_ground\\python\\django_one\\venv', 'C:\\Projects\\play_ground\\python\\django_one\\venv\\Lib\\site-packages'] Server time: Fri, 05 Apr 2024 08:19:46 +0000 can you help me with issue thnx all -
Question about auto re-issue Access token in Django (simple jwt)
Hello I have a question about JWT in backend django, so I'm leaving a question. (I'm using Simple-jwt package.) Currently, when the user logs in, both access and refresh tokens are being sent to the response body. (I'm trying to send refresh tokens to the header because there's a security problem.) At this time, when the access token expires, I know the procedure to reissue it through refresh, but I don't know how django will handle it automatically. I wanted to go to the procedure of reissuance before the expiration time of access at the front(web/app), but there is a problem that the access token increases indefinitely. When the front sends a general API request, I know that if client send both access and refresh, the access token will expire through the IsAuthenticated procedure at the back server, and I understand that it automatically reissues the access token through refresh and performs the previously requested API. So I tried Googling this, but I didn't see the code that automatically reissued it, only sending it to the endpoint (/jwt-token-auth/refresh/) provided by default. However, if I get caught in IsAuthenticated, the server spit out the error because it's invalid token, how do … -
How do I create separate fields for normal users and admins users in Django?
I have a custom user model that has fields common for both a normal user and an admin (which are email[used to log into the system], first name, and last name). But I want to give additional fields for the normal users of the system. How do I achieve this? class UserAccountManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) email = email.lower() user = self.model( email=email, first_name=first_name, last_name=last_name ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, password=None): user = self.create_user(email, first_name, last_name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) profile_picture = models.ImageField(default='default.jpg', upload_to='profilePictures', null=True, blank=True) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email + " | " + self.first_name Ii tried the above code but it only create a one single table for both normal users and admins -
Unable to fetch data from django to react
So I am creating a login page. I have created my models as well as the views and endpoints. When logging in, I was trying to fetch the data from the backend using django to verify the login credentials entered, But I get a runtime error TypeError: Failed to fetch at HandleSubmit I am successful in registering my user, I have checked in the database to make sure that the user exists A basic overview of my setup. I have a model LoginDetails, which has been set as the AUTH_USER_MODEL in settings.py. Here is my model class LoginDetails(AbstractUser): user_data = models.OneToOneField(UserData, on_delete=models.CASCADE, null = True) username = models.CharField(max_length=255, unique=True, null=True) password = models.CharField(max_length=255, null=True) # Note: It's recommended to use hashed passwords in production USERNAME_FIELD = 'username' def __str__(self): return self.username Here is my login.js (Only posting the relevant info) `const handleSubmit = async (event) => { event.preventDefault(); const response = await fetch('http://127.0.0.1:8000/api/login/', { method: 'POST', headers: {'Content-Type': 'application/json'}, credentials: 'include', body: JSON.stringify({ formData }) }); const content = await response.json(); setRedirect(true); props.setName(content.name); };` And the view associated with my endpoint api/login class LoginView(APIView): def post(self, request): username = request.data.get('username') password = request.data.get('password') user = LoginDetails.objects.filter(username=username).first() if user is None: … -
HTML Content is not loading in Django Application
See in the image, my html content is not loading in django project Till yesterday it was working fine. dont know what happened in a night. Noone has touched my PC but dont know why am I getting this issue. Please help me. This is very urgent -
How can I solve N+1 problem double prefetch_related using order_by in Django?
In models.py the simple structure is... Model A(parent of B) <- Model B(parent of C) <- Model C And in views.py, I want to use both prefetch_related in B,C and order_by in b. a_obj = A.objects.prefetch_related(Prefetch("b__c", queryset=B.objects.all().order_by("-order"))) but in serializers.py, I cannot access to c's data. def get_data(self, group): for b in group.b.all(): print(b.c.all()) # ===> result: queryset [B object(pk)] And I also tried another way in views.py and serializers.py # views.py a_obj = A.objects.prefetch_related("b__c") # serializers.py def get_data(self, group): for b in group.b.all().order_by("-order"): print(b.c.all()) # ===> N+1 query occurred But I have N+1 problem. What should I do? -
Django 5: Within the form, filter data with another field of the same form
I have a question that I can't solve. Form: I choose country I choose region 1 I choose region 2 Based on the country I chose, how can I filter the data for region 1? Code fk_country = forms.ModelChoiceField( label="Pais", queryset= PteCountry.objects.all(), required=True, error_messages={"required": "Introduzca Pais"}, ) fk_region_1 = forms.ModelChoiceField( label="Region 1", queryset= PteRegion1.objects.filter(fk_country_id__in=PteCountry.objects.filter(id=**?????**).values_list('id')), required=True, error_messages={"required": "Introduzca Region 1"}, ) filter a list of values, based on a field of the same form -
annotating an object with a list of objects related to it but filtered down
I have the following objects (simplified just for this question) class Object1(models.Model): users_assigned_to_object1 = models.ManyToMany(Users, related_name='objects') sub_object = models.ForeignKey(SubObject1) class Users(models.Model): first_name = models.CharField(max_length=1000) class SubObject1(models.Model): sub_object_name = models.CharField(max_length=1000) class SubObject2(models.Model): sub_object_1 = models.ManyToMany(SubObject1) class SubObject3(models.Model): sub_object_2 = models.ManyToMany(SubObject3) role_name = models.CharField(max_length=1000) user = models.ForeignKey(Users, related_name='sub_object_relation') For more complex reasons that do not matter right now, I need to be able to annotate Object1 with the users that are users assigned to object 1 AND where those users have role_name=ADMIN for at least one of the SubObject3 models that are related to Object1. E.g. I'm trying to get to something like this: Object1.objects.annotate(admin_users=X) What goes on X? I'm on Django 4.2 and using a Postgres DB I tried using SubQueries but they don't respond with lists (and this can return a list) and tried doing things with Django Conditional expressions (e.g. ArrayAgg, When) but couldn't really get to the right solution on this one. -
Field 'id' expected a number but got dict when seeding database django
I'm looking for a way to store a question fetched from an external API to be stored in a model called Question. My views.py module does that by requesting data based on user's question difficulty choice, then renders what's fetched in a form. It's a pretty straightforward method but for some reason I get Field 'id' expected a number but got {'type': 'multiple'...}. I deleted a code that intended to create a another model singleton that was interfering with this implementation from last answer of this question. Then I ran ./manage.py makemigrations and ./manage.py migrate to reflect changes but the exception was again raised. After that, I deleted migrations.py and their cached files to run the same two commands and nothing changed. Can anyone point out what I'm missing/doing wrong please? models.py from django.db import models class Question(models.Model): type = models.TextField() difficulty = models.TextField() category = models.TextField() question = models.TextField() correct_answer = models.TextField() incorrect_answers = models.TextField() views.py from django.shortcuts import render, HttpResponse from .forms import QuestionForm, QuestionLevelForm from urllib.request import URLError from .models import Question import requests def process_question(request): if "level" in request.POST: return fetch_question(request) elif "answer" in request.POST: return check_answer(request) else: form = QuestionLevelForm() return render(request, "log/question.html", {"form": form}) … -
Return http status code 401 when login with invalid credentials
How would i go about changing an django application that uses allauth so that it returns 401 response when invalid login credentials are provided? I have tried to put custom logic in a custom ModelBackend but found no way to actually modify the response status code there. I have also tried to put custom logic in a CustomAccountAdapter.authentication_failed but same issue there i found no way to change the status code. -
Please how to I fix primary key url issue in Django
I decided working of an API using Django Rest Framework and I can be able to view all the data in the endpoint but when I try to call just one of the data using a primary in the URL, I get a 404 error These are my codes. Please I need help[[[[[[Codes and the error dispayed](https://i.stack.imgur.com/yzFca.jpg)](https://i.stack.imgur.com/kbBLY.jpg)](https://i.stack.imgur.com/bSHbk.jpg)](https://i.stack.imgur.com/hjn9A.jpg)](https://i.stack.imgur.com/5E2WX.jpg)](https://i.stack.imgur.com/gdnVC.jpg) -
Django admin add form produces TypeError: __str__ returned non-string (type __proxy__)
I got the followin error message and I do not understand the issue. Further, I do not know where to start my search. TypeError at /admin/fixeddata/persondetails/add/ str returned non-string (type proxy) Request Method: GET Request URL: http://127.0.0.1:8000/admin/fixeddata/persondetails/add/ Django Version: 5.0.4 Exception Type: TypeError Exception Value: str returned non-string (type proxy) Exception Location: C:\Projects\Plattform\venv\Lib\site-packages\django\forms\models.py, line 1523, in label_from_instance Raised during: django.contrib.admin.options.add_view Python Executable: C:\Projects\Plattform\venv\Scripts\python.exe Python Version: 3.11.1 Python Path: ['c:\Projects\Plattform\project', 'C:\Python\python311.zip', 'C:\Python\DLLs', 'C:\Python\Lib', 'C:\Python', 'C:\Projects\Plattform\venv', 'C:\Projects\Plattform\venv\Lib\site-packages'] Server time: Thu, 04 Apr 2024 20:46:57 +0200 I already used str() in all my overrides of the str method of my model classes. I do not know what the "type proxy" means and when proxy is returned. In a forum entry I read something about a potential conflict with the gettext_lazy method. I use that as well in my model class. I tried to import gettext instead but that the error remains unchanged. I do not know for what type of error I am looking. It would be great if anyone could give me a hint. -
WebSocket 'Connection reset by peer, uri'
I have a Flutter app, where I'm trying to handshake with my django backend websocket. However, I'm receiving the following error: [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: HttpException: Connection reset by peer, uri = http://myIP:8000/ws/chat_app/44HsUd/ Here is my Django code, where the receive method is never hit (the print statement never shows in the terminal) # consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from .utils import get_room class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['unique_id'] self.room_group_name = f'video_{self.room_name}' # Join room group self.room_obj = await database_sync_to_async(get_room)(unique_id=self.room_name) await (self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() async def disconnect(self, close_code): # Leave room group await (self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) async def receive(self, text_data): # Receive video URL from client print('test in receive') text_data_json = json.loads(text_data) video_url = text_data_json['video_url'] # Broadcast video URL to all clients in room await self.channel_layer.group_send( self.room_group_name, { 'type': 'video_url', 'video_url': video_url } ) async def video_url(self, event): # Send video URL to client video_url = event['video_url'] await self.send(text_data=json.dumps({ 'video_url': video_url })) I'm trying to make a basic video player in Flutter, here is my code there import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:web_socket_channel/io.dart'; import 'package:web_socket_channel/web_socket_channel.dart'; import 'package:youtube_player_flutter/youtube_player_flutter.dart'; class VideoStreamPage extends StatefulWidget { final String roomName; const VideoStreamPage({Key? key, required this.roomName}) … -
Static Files not loading Django + Azure Web App
https://github.com/EPICS-HDR/New-Code-Layout Thats the repo I have tried everything on the internet. (New to web development, need help) STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'services' /'static', ] STATIC_ROOT = os.path. join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage" in urls.py: ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) standingrock.azurewebsites.net -
N+1 problems in double reverse foreign key in Django
I have N+1 problem in double reverse foreign key in Django(DRF). In models.py for example, class A(models.Model): name = models.CharField() class B(models.Model): a = models.ForeignKey(A, related_name="b") name2 = models.CharField() class C(models.Model): b = models.ForeignKey(B, related_name="c") name3 = models.CharField() Then in the middle of views.py, I called model A such as... a_obj = AA.objects.prefetch_related("b__c").get(pk=pk) And in the middle of serializers.py... def get_inform_prefetch_related(self, group): result = [] for b in group.b.all(): for c in b.c.all(): result.append({"b": b.name2, "c": c.name3}) In these codes, both b and c have N+1 problem. What should I do? -
Why Inclusion tags not working in Django?
I want to use inclusion tags to display the sidebar, but nothing is displayed. templatetags/sidebar_tags.py from ..models import Post from django import template register = template.Library() @register.inclusion_tag('blog/include/post-category.html') def post_category(): return {'posts': Post.objects.all()} post-category.html <div class="single-sidebar-widget post-category-widget"> <h4 class="category-title">Post Categories</h4> <ul class="cat-list"> {% for category in posts.categories.all %} <li> <a href="#" class="d-flex justify-content-between"> <p>{{ category.name }}</p> <p>37</p> </a> </li> {% endfor %} </ul> </div> home.html {% load sidebar_tags %} {% post_category %} I think the code is ok but I don't know why it works -
django.db.utils.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib '/app/.apt/usr/lib/libmsodbcsql-18.3.so.2
My django heroku app is building but fails during the release process with the error below. django.db.utils.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib '/app/.apt/usr/lib/libmsodbcsql-18.3.so.2.1' : filo.2.1' : file not found (0) (SQLDriverConnect)") I am using vscode in windows. I followed the CodeWithMosh process and I can run the db in dev mode on my machine. Below is a snip of the requirements.txt file. Django==5.0.3 django-filter==23.5 django-heroku==0.3.1 docopt==0.6.2 pymssql==2.2.11 pyodbc==5.1.0 sqlparse==0.4.4 virtualenv==20.25.1 My AptFile is configuration is below. `unixodbc unixodbc-dev https://packages.microsoft.com/ubuntu/22.04/prod/pool/main/m/msodbcsql18/msodbcsql18_18.3.2.1-1_arm64.deb` I have installed the MSSQL build pack and the associated UBUNTU build packs. django.db.utils.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib '/app/.apt/usr/lib/libmsodbcsql-18.3.so.2.1' : filo.2.1' : file not found (0) (SQLDriverConnect)") The first buildpack: ``https://github.com/heroku/heroku-buildpack-apt.git The second buildpack: ``https://github.com/heroku/heroku-buildpack-python.git The last buildpack: ``https://github.com/heroku-softtrends/heroku-python-pyodbc-buildpack.git Heroku support states this outside of their support (which I find... uh unfortunate). Any thoughts or suggestions are most welcome. Thx I have re-ran pipenv install pyodbc and pip freeze requirements.txt, but still have the same release fail after a successful build. remote: -----> Starting adding ODBC Driver 18 for SQL Server remote: -----> copied libmsodbcsql-18-* remote: -----> copied msodbcsqlr18.rll remote: -----> copied profile.d remote: -----> Finished adding ODBC Driver 18 for SQL Server remote: -----> Discovering process types … -
Django cookiecutter docker backups not working
I have a django cookiecutter docker project and It's on github. I have it on my windows laptop and on the company's windows server. The backups are working fine on my laptop when I do docker compose -f production.yml exec postgres backup but on the windows server the terminal seems to freeze up, it just stops and looks like nothing is happening. On my laptop it looks like this PS C:\work\*******\*******> docker compose -f production.yml exec postgres backup Backing up the 'app' database... SUCCESS: 'app' database backup 'backup_2024_04_03T19_13_30.sql.gz' has been created and placed in '/backups'. PS C:\work\*******\*******> on the windows server it looks like this. PS C:\work\*******\*******> docker compose -f production.yml exec postgres backup Also i am sure i have the same version of my project on both of them -
Origin checking failed - http://localhost:8000/ does not match any trusted origins
I have been struggling with a CORS issue with login form POST request coming from React dev server to my django backend where I am using Django's LOginView module for login requests API. These are my settings for settings.py CORS_ALLOW_METHODS = ( "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ) CORS_ALLOW_HEADERS = ( "accept", "authorization", "content-type", "user-agent", "x-csrftoken", "x-requested-with", ) CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', ] CORS_TRUSTED_ORIGINS = [ 'http://localhost:3000', ] CSRF_TRUSTED_ORIGINS = [ 'http://localhost:3000', ] CORS_ORIGINS_WHITELIST = [ 'http://localhost:3000', ] and for react I am implementing a proxy in package.json "proxy": "http://localhost:8000/", my api for user token retrieval works fine but I believe something is wrong with the CSRF verification. Kindly take a look at the title for the arisen error. Thanks. I have alreaady tried the settings reffered in documentation : https://pypi.org/project/django-cors-headers/ and someone facing the similar problem in the forum https://forum.djangoproject.com/t/origin-checking-failed-with-ssl-https/20158/13 -
Django content type showing data in `app_label: model` format in the admin dashboard
I have recently updated my application Django version from 2.2.24 to 5.0.3 after upgrading the Django I have now started getting the content_type data in this format `app_label: model` in my Django dashboard, before the update the in Django admin the content_type data was shown in this format `model`. This is the ContentType model defination, and it is imported from `django.contrib.contenttypes.models` class ContentTypeManager(BaseManager[ContentType]): def get_by_natural_key(self, app_label: str, model: str) -> ContentType: ... def get_for_model( self, model: type[Model] | Model, for_concrete_model: bool = ... ) -> ContentType: ... def get_for_models( self, *models: Any, for_concrete_models: bool = ... ) -> dict[type[Model], ContentType]: ... def get_for_id(self, id: int) -> ContentType: ... def clear_cache(self) -> None: ... class ContentType(models.Model): id: int app_label: models.CharField[Any] = ... model: models.CharField[Any] = ... objects: ClassVar[ContentTypeManager] = ... permission_set: Manager[Permission] @property def name(self) -> str: ... def model_class(self) -> type[Model] | None: ... def get_object_for_this_type(self, **kwargs: Any) -> Model: ... def get_all_objects_for_this_type(self, **kwargs: Any) -> QuerySet[Any]: ... def natural_key(self) -> tuple[str, str]: ... **As per this change my custom build functions are now breaking. Before it used to be like this And after the update(the data is a bit different but the format is changed) This is the admin … -
How do I configure i18n with django rosetta in react?
I'm writing the frontend code using react. I need to change the language on the site using Django. I don't know where to start. Should i use i18next? How can I configure if I need to use it import i18n from "i18next"; import detector from "i18next-browser-languagedetector"; import backend from "i18next-http-backend"; import { initReactI18next } from "react-i18next"; i18n .use(detector) .use(backend) .use(initReactI18next) // passes i18n down to react-i18next .init({ fallbackLng: "en", // use en if detected lng is not available saveMissing: true // send not translated keys to endpoint }); export default i18n; -
Django debug toolbar not catch query from local db
django = "4.0.8" django-debug-toolbar = "^4.3.0" drf-spectacular = "^0.26.5" Django container is connected to local database. So when call API then return response data that get from local database. But no sql query on debug toolbar panel. When I enter SQL page then only this statements are exist. SQL queries from 0 connections No SQL queries were recorded during this request. I set host.docker.internal to connect to container to local db that on host. extra_hosts: - "host.docker.internal:host-gateway" .local.env DB_ENGINE="django.contrib.gis.db.backends.postgis" DB_HOST="host.docker.internal" DEBUG=True I assigned True and False to INTERCEPT_REDIRECTS. But not worked Why django debug toolbar can not catch sql query? local_settings.py from dotenv import load_dotenv load_dotenv(".env.local") from .base_settings import * import socket DEBUG = True LOGGING["loggers"]["django"]["handlers"] = ["console", "file"] CORS_ALLOWED_ORIGINS = [ "http://localhost:8000", "http://127.0.0.1:8000", "http://localhost:80", "http://127.0.0.1:80", "http://localhost:3000", "http://127.0.0.1:3000", "http://host.docker.internal:8000", ] CORS_ALLOW_METHODS = [ "GET", "POST", ] INTERNAL_IPS = [ "*", "127.0.0.1", "localhost", "192.168.0.1", "10.0.2.2", "host.docker.internal", ] hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS += [".".join(ip.split(".")[:-1] + ["1"]) for ip in ips] def show_toolbar(request): return True DEBUG_TOOLBAR_CONFIG = { "INTERCEPT_REDIRECTS": True, "SHOW_TOOLBAR_CALLBACK": show_toolbar, } if DEBUG: import mimetypes mimetypes.add_type("application/javascript", ".js", True) base_settings.py #... INSTALLED_APPS = [ "django.contrib.staticfiles", "drf_spectacular", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "real_estate", "accounts", "modu_property", "django_celery_beat", "rest_framework", "rest_framework_simplejwt", "django.contrib.gis", "debug_toolbar", "corsheaders", …