Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django HttpStreamingResponse Not Streaming
I have a very interesting issue with the Django HttpStreamingResponse. Our server calls OpenAI Text Completion API in streaming mode, upon receiving the chunks from OpenAI, we incrementally parse the chunks and stream complete JSON objects back to our clients. Below are some code snippets: views.py class StreamViewSet(ModelViewSet): ... def stream(self, request): ... json_stream = agent.get_json_objects() return StreamingHttpResponse(json_stream, content_type="application/json") agents.py def stream(self): yield from self.json_agent.get_json_stream() json_agent.py def get_data_stream(self): # This calls OpenAI text completion API with stream=True stream_response = self.get_text_completion(user_preference, stream=True) # Create an incremental json parser json_stream_parser = JsonStreamParser() for chunk in stream_response: if chunk.choices and chunk.choices[0].delta.content is not None: json_stream_parser.feed(chunk.choices[0].delta.content) yield from json_stream_parser.parse() json_parser.py class JsonStreamParser: """A simple JSON stream parser that can parse a stream of JSON objects. Note it only works for an array of JSON objects, which means the input must contain a valid JSON array, at any point of the stream, that starts with '[' and ends with ']'. It will parse the JSON objects in the array and ignores anything outside of the array. """ def __init__(self): self.buffer = "" self.index = 0 self.open_braces = 0 self.start_index = -1 self.array_started = False def feed(self, data): self.buffer += data def parse(self): parsed = [] … -
Custom Django admin login with django allauth package
I want a functionalities where when user login to admin page, either using username and password, or using google sso (using allauth package). they still need to go for a certain check. Now I have this views where i state my checks: views.py def custom_login(request): if request.method == 'POST': form = AuthenticationForm(request, request.POST) if form.is_valid(): user = form.get_user() # Check if the user belongs to a specific group print(user) check_in_wd = check_user_in_wd(user) if (user.groups.exists() or user.is_staff) and check_in_wd: login(request, user) return redirect('/admin/') # Redirect to admin dashboard after successful login else: messages.error(request, 'You are not authorized to access the admin page.') else: messages.error(request, 'Invalid username or password') else: form = AuthenticationForm() return render(request, 'admin/login.html', {'form': form}) urls.py urlpatterns = [ path('grappelli/', include('grappelli.urls')), # grappelli URLS path('admin/login/', custom_login, name='custom_login'), path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), ] login.html - just for extra refs <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>App</title> </head> <body> {% extends "admin/login.html" %} {% load static %} {% load i18n %} {% block content %} <div id="content-main"> <form id="login-form" method="post" action="{% url 'admin:login' %}" novalidate> {% csrf_token %} {{ form.non_field_errors }} <div class="form-row"> <label for="id_username">{{ _('Username') }}:</label> {{ form.username }} </div> <div class="form-row"> <label for="id_password">{{ _('Password') }}:</label> {{ form.password }} … -
Django queryset filter data by timestamp range at last one hour
I am trying to filter data from the Django queryset where the timestamp range has to be exactly last seven days at the last one hour. For example, I want to filter out data from today (March 31st, 2024) until March 24th, 2024 but only within the last hour (10:00 - 11:00 a.m.). What I have done so far, yet still no further improvements: qs = SuccessRateTodayData.objects.select_related('region')\ .order_by('-timestamp', 'region__region_name')\ .filter(Q(timestamp__range=(start, end))) I have tried using raw query in PostgreSQL. It's something like this: SELECT regionname, round(avg(completed)::numeric, 2) avg_completed, round(avg(failed)::numeric, 2) avg_failed FROM ( SELECT timestamp2, regionname, completed, failed, num_read, numofdata FROM "SuccessRateTodayData" WHERE timestamp2 > current_date - interval '7 days' AND (timestamp2::time BETWEEN '10:00:00' AND '11:00:00') ORDER BY regionname, timestamp2 ) t GROUP BY regionname Expected Result: Any help would be appreciated. Thank you. -
How to fix the issue with some post functions not working during autopagination?
I need help solving a problem with automatic pagination. When automatic pagination occurs from the home_list.html template to the home.html template, all functions of the template stop working, even though the template itself is paginated correctly. The functionality stops working after pagination, namely: "edit" and "delete" the published post, "Add comment", "Edit comment", "Save edited comment", "Delete comment". In the home.html template, these functions work in the {% for post in post_lists %} loop, but after automatic pagination from the home_list.html template in the {% for post in posts %} loop, these functions do not work. How can I fix this? home.html <div id="post_contenter"> {% for post in post_lists %} <div class="post_content" id="post_content"> <!-- Add identifier post_content --> <div class="post_header"> <div class="post_user_avatar"> {% if post.author.avatar %} <img style="width:50px; height: 50px;" src="{{ post.author.avatar.url }}" class="user-picture-small"> {% else %} <img style="width:50px; height: 50px;" src="{% static 'twippie/img/avatar.png' %}" class="card_user_picture_small"> {% endif %} </div> <div class="post_user_info"> <div class="post_user_fullname"><a href="{% url 'user:profile_username' post.author.username %}" class="post_user_fullname_style">{{ post.author.first_name }} {{ post.author.last_name }}</a></div> <div class="post_user_username"><a href="{{ user_profile.username }}" class="post_user_nickname_style">@{{ post.author }}</a> {% if post.author.verification %} <span class="verified_user_small"></span> {% endif %} </div> <div class="post_user_date"><a href="{{ post.get_absolute_url }}" class="post_user_date_style">{{ post.time_create }} {{ post.time_create|naturaltime }}</a></div> </div> </div> <div class="post_user_more"> <div class="dropdown … -
Django Admin Panel and Sub URLs Returning 404 Error on Deployment
have recently deployed my Django project to a server, and while the index URL (mannyebi.com) loads correctly along with static files, accessing sub URLs such as mannyebi.com/blogs or even the admin panel (mannyebi.com/admin) results in a 404 error. Locally, the project runs smoothly, indicating the issue may stem from the deployment configuration. I've ensured that all necessary URL patterns are defined in the urls.py files and that Django's admin app is properly installed and configured. However, despite these measures, I'm still encountering difficulties accessing sub URLs beyond the homepage. Is there a specific configuration step or server setting that I might be overlooking to resolve this 404 error and enable access to sub URLs on my deployment? Any insights or troubleshooting suggestions would be greatly appreciated. I deployed my Django project to a server. Upon navigating to sub URLs such as mannyebi.com/blogs or mannyebi.com/admin, I encountered a 404 error. I verified that all necessary URL patterns were defined in urls.py and that Django's admin app was properly configured. I expected these URLs to load correctly, similar to how they did on my local development environment. However, despite these efforts, the 404 errors persisted. I'm seeking guidance on resolving this issue … -
How to return HTTP Get request response from models class in Django project
I am trying to Get a response from the OpenAi assistants API using a Django project. I implement a model class inside models.py as such: from django.db import models from typing_extensions import override from openai import AssistantEventHandler from django.http import HttpResponse # Create your models here. class Eventhandler(models.Model,AssistantEventHandler): class meta: managed = False @override def on_text_created(self, text) -> None: print(f"\nassistant > ", end="", flush=True) @override def on_text_delta(self, delta, snapshot): print(delta.value, end="", flush=True) def on_tool_call_created(self, tool_call): print(f"\nassistant > {tool_call.type}\n", flush=True) def on_tool_call_delta(self, delta, snapshot): if delta.type == 'code_interpreter': if delta.code_interpreter.input: print(delta.code_interpreter.input, end="", flush=True) if delta.code_interpreter.outputs: print(f"\n\noutput >", flush=True) for output in delta.code_interpreter.outputs: if output.type == "logs": print(f"\n{output.logs}", flush=True) Now, what is important is that the Eventhandler class sends the response back to the client! I am a getting an exception of type: ValueError: The view theassistantcallerapp.views.callerview didn't return an HttpResponse object. It returned None instead. Now, callerview is the view inside views.py. It maps to the URL that will start the GET request to the OpenAi Assistants API. This implementation I am using is for streaming responses. Now, here is the view insides views.py and NOTICE HOW THE EVENTHANDLER CLASS IS USED #inside views.py # this is callerview(request, paramm): thread = … -
Issue with Quantity Increment in Django E-commerce Cart
Description: I'm encountering an unexpected behavior in my Django e-commerce website where the quantity of items in the cart increments at an exponential rate instead of a linear one. Here's a breakdown of the problem and the relevant code snippets: Problem Description: When adding an item to the cart, the quantity appears to double with each click of the "add" button. For instance, if I add an item once, it shows a quantity of 3 instead of 1. Then, upon adding it again, the quantity jumps to 6 instead of 2, and so forth. Similarly, when decreasing the quantity using the "remove" button, it doesn't decrement linearly but exhibits similar exponential behavior. Code Snippets: cart.html: This snippet shows the HTML code responsible for displaying the quantity and buttons to add or remove items from the cart. <div class="li-cartstyle cartbodyinformation-quantity"> <p class="quantity-input">{{ item.quantity }}</p> <div class="cartquantity-buttons"> <i data-product={{ item.product.id }} data-action="add" class="update-cart change-quantity fa-solid fa-angle-up"></i> <i data-product={{ item.product.id }} data-action="remove" class="update-cart change-quantity fa-solid fa-angle-down"></i> </div> cart.js: This JavaScript code handles the interactions with the cart, such as adding or removing items. // var user = '{{request.user}}' var updateBtns = document.getElementsByClassName('update-cart') var user = isAuthenticated ? 'AuthenticatedUser' : 'AnonymousUser'; for(var i=0; i … -
Can't install Pipenv on Windows
i'm building the backend of an app in python and i wanted to use Django, the problem is, i installed pipenv with pip3 the first time and it run smoothly, now if i try to install with pip only it tells me: Requirement already satisfied: pipenv in c:\users\marco\appdata\roaming\python\python39\site-packages (2023.12.1) Requirement already satisfied: virtualenv>=20.24.2 in c:\python39\lib\site-packages (from pipenv) (20.25.1) Requirement already satisfied: certifi in c:\users\marco\appdata\roaming\python\python39\site-packages (from pipenv) (2024.2.2) Requirement already satisfied: setuptools>=67 in c:\users\marco\appdata\roaming\python\python39\site-packages (from pipenv) (69.2.0) Requirement already satisfied: platformdirs<5,>=3.9.1 in c:\python39\lib\site-packages (from virtualenv>=20.24.2->pipenv) (4.2.0) Requirement already satisfied: distlib<1,>=0.3.7 in c:\python39\lib\site-packages (from virtualenv>=20.24.2->pipenv) (0.3.8) Requirement already satisfied: filelock<4,>=3.12.2 in c:\python39\lib\site-packages (from virtualenv>=20.24.2->pipenv) (3.13.3) WARNING: You are using pip version 21.2.3; however, version 24.0 is available. You should consider upgrading via the 'C:\Python39\python.exe -m pip install --upgrade pip' command. but if i try to run pipenv --version powershell tells me: pipenv : Termine 'pipenv' non riconosciuto come nome di cmdlet, funzione, programma eseguibile o file script. Controllare l'ortografia del nome o verificare che il percorso sia incluso e corretto, quindi riprovare. In riga:1 car:1 + pipenv + ~~~~~~ + CategoryInfo : ObjectNotFound: (pipenv:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException (wich by the way is the "not recognized as the name of … -
use dict from python in django html template and also in js
I am having a dict statistics in my view.py and give it as param in my context to my index.html. There I want to use it in my html like {{ statistics.key1 }}. But I also want to use it in js. When using json.dumps like this in my view.py: "statistics": json.dumps(statistics, cls=DjangoJSONEncoder), I can use it like this in my js: var statistics = JSON.parse('{{ statistics | escapejs }}'); But then I can't use it as a dict anymore in my html. Makes sense, as it is now a JSON-String. But when I just pass it like a dict, I can use it in my html. but var statistics = '{{ statistics | escapejs }}' gives me a JSON with single quotes so I can't just parse it. How can I do both? Still use the dict as normal in my HTML and also parse it to use it in js? -
'pyodbc.Cursor' object has no attribute 'callproc', mssql with django
I cannot execute a procedure stored on mssql server from django. Here is the configuration for the db DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), 'OPTION':{ 'driver': 'ODBC Driver 17 for SQL Server', 'trusted_connection': 'yes' } } } In my view: def test(request): if request.method == "POST": with connection.cursor() as cursor: P1 = request.data["p1"] P2 = request.data["p2"] try: cursor.callproc('[dbo].[SP_TEXT]',[P1,P2]) if cursor.return_value == 1: result_set = cursor.fetchall() print(result_set) finally: cursor.close() return Response({"msg":"post"}) else: return Response({"msg": "get"}) I use sql server standard 2022 Need help please -
Django Bootstrapv5 carousel multiple item problem
I want my carousel items to contain a maximum of 5 card tags. However, when I add more cards and it exceeds five, it doesn't create another carousel item, but simply overflows into the same carousel. How i can fix this problem. This is my code: <div class="carousel-box"> <div id="carousel-1" class="carousel slide" data-bs-interval="false" data-bs-wrap="false"> <div class="carousel-inner"> {% for knowledge in knowledges %} <div class="carousel-item {% if forloop.first %}active{% endif %}"> <div class="row"> {% for photo in photo01s %} {% if photo.category01 == knowledge %} <div class="card" style="background-image: url('{{ photo.image01.url }}');"></div> {% endif %} {% endfor %} </div> </div> {% endfor %} </div> </div> I have written it like this, but it's not effective. <div class="carousel-box"> <div id="carouselExample" class="carousel slide" data-bs-interval="false" data-bs-wrap="false"> <div class="carousel-inner"> {% for knowledge in knowledges %} {% if forloop.first %} <div class="carousel-item active"> {% else %} <div class="carousel-item"> {% endif %} <div class="row"> {% with photo_count=0 %} {% for photo in photo01s %} {% if photo.category01 == knowledge %} {% if photo_count < 5 %} <div class="card" style="background-image: url('{{ photo.image01.url }}');"> </div> {% endif %} {% increment photo_count %} {% endif %} {% endfor %} {% endwith %} </div> </div> {% endfor %} </div> </div> -
Django socketio process
I'm dealing with a little problem that I need to solve. I have an application in Django and I need a websocket, but I don't like Django channels, so I created a socket server in Flask and I'm trying to connect Django to it, by creating middleware that when called starts a process that sends messages through the process what it has in the queue But either the shared variable doesn't work or the process itself doesn't work properly. Please if you have any advice or solution write also how to terminate the process with socket when django terminates This is my code: socket.py --- import socketio import json from project.settings import SOCKET_CONFIG, MANAGER from multiprocessing import Process sio = socketio.Client() class Socket: queue = MANAGER.list() def __init__(self, get_response): self.get_response = get_response thread = Process(target=Socket.process_loop, args=()) thread.start() def __call__(self, request): return self.get_response(request) @staticmethod def process_loop(): sio.connect('http://{}:{}'.format(SOCKET_CONFIG["host"],SOCKET_CONFIG["port"])) while True: try: import time time.sleep(1) data = Socket.queue.pop(0) sio.emit('message', data) except BaseException as e: print(e) settings.py --- import os, subprocess from multiprocessing import Process, Manager MANAGER = Manager() SOCKET_CONFIG={ "host":"localhost", "port":8001 } ... -
Unable to get Docker with React and Django to work in Ubuntu - forbidden access
I am trying to get my React and Django project that is using docker-compose to work on AWS Ubuntu. It works on my mac. However, I cant get it working on my IP. I have allowed port 80 inbound traffic. Here are the docker-compose up logs https://gist.github.com/axilaris/5844a146a08ae80256f064572a1f0ab6 One thing I noticed is nginx where it serves the React files seems to be forbidden: nginx_1 | 2024/03/31 14:57:00 [error] 29#29: *1 directory index of "/var/www/frontend/" is forbidden, client: 172.20.4.193, server: , request: "GET / HTTP/1.1", host: "172.21.4.130" nginx_1 | 172.20.4.193 - - [31/Mar/2024:14:57:00 +0000] "GET / HTTP/1.1" 403 153 "-" "ELB-HealthChecker/2.0" "-" nginx_1 | 2024/03/31 14:57:01 [error] 29#29: *2 directory index of "/var/www/frontend/" is forbidden, client: 172.20.1.172, server: , request: "GET / HTTP/1.1", host: "172.21.4.130" nginx_1 | 172.20.1.172 - - [31/Mar/2024:14:57:01 +0000] "GET / HTTP/1.1" 403 153 "-" "ELB-HealthChecker/2.0" "-" Here is my docker-compose.yaml file version: '3.7' services: # Redis redis: image: redis:alpine container_name: redis ports: - "6379:6379" backend: volumes: - .:/django - static:/static env_file: - .env build: context: ./backend ports: - "8000:8000" container_name: backend_container frontend: build: context: ./frontend volumes: - frontend:/app/build container_name: frontend_container nginx: build: context: ./nginx volumes: - static:/static - frontend:/var/www/frontend ports: - "80:80" depends_on: - redis - backend … -
Root path analogue in uWSGI as in Uvicorn
Uvicorn has the option --root-path (https://www.uvicorn.org/settings/#http) that helps a lot if the application is mounted to a specific path, distinct to /. For example, in case of a Django application I can run it with: uvicorn myproj.asgi:application --host=localhost --port=8001 --root-path="/myproj-custom-path" So if I configure the Nginx location /myproj-custom-path/ as proxy_pass http://localhost:8001/, I can access the application by http://localhost:80/myproj-custom-path with all the functionality, including the Admin panel, without the need to specify the root path anywhere else in the project. Is there a similar option or a way to do the same with uWSGI? -
Django register function accepting a new user while the login function can't find it
I'm creating a site using django, python and html. I have an app called account which I have currently written two functions for: register and login_view. My register function works properly, accepting a user unless their username is already taken or their two passwords are not a match. However, my login_view function doesn't seem to recognize the same user that has just been created in the register page, giving me this error: return render(request, 'account/login.html', {'error': 'Wrong username or password.'}) Here are the files inside my account folder I've worked on so far: views.py: from django.shortcuts import render from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout def register(request): if request.method == 'POST': if request.POST['password1'] == request.POST['password2']: the_username = request.POST['username'] try: the_user = User.objects.get(username = the_username) return render(request, 'account/register.html', {'error': 'Username already taken. Please choose another one!'}) except User.DoesNotExist: new_user = User.objects.create(username = the_username, password = request.POST['password1']) return render(request, 'account/profile.html') else: return render(request, 'account/register.html', {'error': 'Passwords do not match.'}) else: return render(request, 'account/register.html') def login_view(request): if request.method == 'POST': the_user = authenticate(username = request.POST['username'], password = request.POST['password']) if the_user is not None: login(request, the_user) return render(request, 'account/profile.html') else: return render(request, 'account/login.html', {'error': 'Wrong username or password.'}) else: return render(request, … -
Django - ModuleNotFoundError: No module named 'backend'
I have problem with "ModuleNotFoundError" in my Django app. This problem start when i write serializers.py and other files in my app. All code you see it in my Github This code is without syntax errors because I use PyCharm IDE. When I start server I get this error: PyCharm IDE with terminal after run python server I would appreciate any comments on where I made a mistake. I expect my code to work correctly. -
Does Python being a loosely typed programming language make it less secure?
We have this huge issue as a team in choosing a programming stack to develop a web application for a client, one group prefers Django, while the other prefer Springboot claiming that python is a loosely typed programming language, and that makes it less secure unlike Java. In terms of security is Java better than Python? -
sorl-thumbnail adds a background color when padding is used
I'm using sorl-thumbnail and it works as expected except for when I use padding (which I have to) a white background is added. I know I can change that color, but I want no color (i.e transparency). Is there any hack or another library to fix this? -
Can't connect to local postgresql server from my docker container
I'm trying to connect to local postgresql server from my docker container. I'm using Ubuntu 22.04.4. This is my docker-compose.yml. version: '3' services: ... backend: build: context: '.' dockerfile: 'Dockerfile' ports: - '8000:80' - '8001:8001' env_file: - .env-docker image: backend-django:latest ... This is my .env-docker. DEBUG=True SECRET_KEY=****** DATABASE_USER=postgres DATABASE_NAME=postgres DATABASE_PASSWORD=postgres DATABASE_HOST=host.docker.internal DATABASE_PORT=5432 This is my Dockerfile. FROM python:3.11 ENV PYTHONBUFFERED 1 ... EXPOSE 8000 CMD ["gunicorn", "-b", "0.0.0.0", "config.wsgi"] It was working in Windows but not in Ubuntu now. Is it related to postgresql? I'm using the same version of postgresql and I can connect to local postgresl using PgAdmin. How can I connect to postgresql server from my docker container? -
Why ProductHunt api dont work with Python?
Why i can not work with Product Hunt api in python. My api key is correct `ph = ProductHunt(api_key='WUY0eh1BU_-BnIOtYcFBSEk2UuwUsFCTOXzbZe0CYFY') daily_products = ph.get_daily()` Traceback (most recent call last): File "C:\Users\eesca\PyProjects\solkit\test.py", line 4, in <module> daily_products = ph.get_daily() ^^^^^^^^^^^^^^ File "C:\Users\eesca\PyProjects\solkit\.venv\Lib\site-packages\producthunt\producthunt.py", line 41, in get_daily products = data.get('data', {}).get('posts', {}).get('edges', []) ^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'get' -
why i have to put extra space in before write option selected because it show error if i don't ' option:selected'
data: { product_id: $(this).data('index'), product_quantity: $('#select' + theproductid + ' option:selected').text(), csrfmiddlewaretoken:"{{csrf_token}}", action:'post' }, why in product_quantity where i used option selected i have to put space before option because if i don't put space it show this error product_quantity = int(request.POST.get('product_quantity')) ValueError: invalid literal for int() with base 10: '' can anyone explain. -
Django Arrayfield migration to cloud sql (Postgresql) not creating the column
The project is already running and I tried adding an ArrayField to one of the models. When makemigrations and migrate it applies all migrations but when trying insert a record to the field it says: django.db.utils.ProgrammingError: column "<ArrayField>" of relation "<app>_<model>" does not exist. When checking Cloud SQL (PostgreSQL) have create all columns except for this one in particular. -
how can debugg field id error in the database schema?
TypeError at /contact2/ Field 'id' expected a number but got datetime.datetime(2024, 3, 31, 9, 52, 52, 728466, tzinfo=datetime.timezone.utc). Request Method: POST Request URL: http://127.0.0.1:8000/contact2/ Django Version: 4.2.7 Exception Type: TypeError Exception Value: Field 'id' expected a number but got datetime.datetime(2024, 3, 31, 9, 52, 52, 728466, tzinfo=datetime.timezone.utc). Exception Location: C:\Users\Hamprey Aganyo Ndemo\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\models\fields_init_.py, line 2055, in get_prep_value Raised during: djangoagain.views.contact Python Executable: C:\Users\Hamprey Aganyo Ndemo\PycharmProject\djangoagain\venv\Scripts\python.exe Python Version: 3.12.0 Python Path: ['C:\Users\Hamprey Aganyo Ndemo\PycharmProject\djangoagain', 'C:\Users\Hamprey Aganyo ' 'Ndemo\AppData\Local\Programs\Python\Python312\python312.zip', 'C:\Users\Hamprey Aganyo ' 'Ndemo\AppData\Local\Programs\Python\Python312\DLLs', 'C:\Users\Hamprey Aganyo ' 'Ndemo\AppData\Local\Programs\Python\Python312\Lib', 'C:\Users\Hamprey Aganyo Ndemo\AppData\Local\Programs\Python\Python312', 'C:\Users\Hamprey Aganyo Ndemo\PycharmProject\djangoagain\venv', 'C:\Users\Hamprey Aganyo ' 'Ndemo\PycharmProject\djangoagain\venv\Lib\site-packages', 'C:\Users\Hamprey Aganyo ' 'Ndemo\AppData\Local\Programs\Python\Python312\Lib\site-packages'] Server time: Sun, 31 Mar 2024 09:52:54 +0000 to access the database -
operator class "gin_trgm_ops" does not exist for access method "gin"
psycopg2.errors.UndefinedObject: operator class "gin_trgm_ops" does not exist for access method "gin" Hello everybody, this is the whole message when I try to run pytest on my project which is written in Python/Django + db is postgresql and all sitting inside docker. I build a project on docker with django-cookiecutter template, all settings are default. I put a gin index to one of my string fields, migrations running successfully, pg_trgm extention is being created successfully, but if I try to test my project with pytest I got this error. Here is my pytest.ini [pytest] DJANGO_SETTINGS_MODULE = config.settings.test Here is my test settings file's database configuration: test.py DATABASES['test'] = { # noqa 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'test', 'PASSWORD': 'test', 'USER': 'test', 'HOST': 'localhost', 'PORT': 5454, } This is part of the migration which creates the extention pg_trgm and puts an index to the field given migrations.AddIndex( model_name='<model_name>', index=django.contrib.postgres.indexes.GinIndex(fields=['field_name'], name='field_name_gin_idx', opclasses=['gin_trgm_ops']), ), And this is the whole traceback which I am getting: self = <django.db.backends.utils.CursorWrapper object at 0xffff7244dbb0> sql = 'CREATE INDEX "bank_name_gin_idx" ON "financing_graincreditagrobankworksheet" USING gin ("bank_name" gin_trgm_ops)', params = None ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0xffff7d096b80>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0xffff7244dbb0>}) def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if … -
How do I connect a website to the postgres database?
I am developing a website using django rest framework and react. And I transferred from the test VM to the timeweb cloud virtual cloud and ran into the problem that when connecting to the site, the site starts without information from the postgres database. And also when starting the react web server.the js command "npm run start" outputs an error in browsers on remote client computers: JSON.parse: unexpected character at line 1 column 1 of the JSON data I think this is due to the fact that there is no connection to the database server in postgresql. But, I've already tried adding addresses to ALLOWED HOSTS. I changed both the database and Django. P.S. The username, passwords and addresses are not real. $ cat node_modules/react-scripts/config/webpackDevServer.config.js ... // want to allow setting the allowedHosts manually for more complex setups allowedHosts: disableFirewall ? 'all' : [allowedHost], headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': '*', 'Access-Control-Allow-Headers': '*', }, allowedHosts: [ // Ваш список разрешенных хостов здесь 'localhost', '127.0.0.1', 'IPADDR1' ], ... $ cat settings.py ... ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'IPADDR1', 'HOST1'] ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'BASE', 'USER': 'USER', 'PASSWORD': 'PASSWORD', 'HOST': 'IPADDR1', 'PORT': '5432', } } $ cat /etc/postgresql/14/main/pg_hba.conf ... …