Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ngrok free domain setup
I am just getting started on using ngrok I have created an app/website on Django and trying to test it using ngrok So far the process has been ngrok config add-authtoken ngrok http 8000 Session Status online Account XXXXXXX (Plan: Free) Version 2.3.41 Region United States (us) Web Interface http://127.0.0.1:4040 Forwarding http://<temp-name>.ngrok-free.app -> http://localhost:8000 Forwarding https://<temp-name>.ngrok-free.app -> http://localhost:8000 Connections ttl opn rt1 rt5 p50 p90 0 0 0.00 0.00 0.00 0.00 where I use https://< temp-name >.ngrok-free.app.ngrok-free.app for my testing Through the Domains option in the website I have got a free domain thats <some-free-name>.ngrok-free.app how do I setup/run so that ngrok will use this domain, which will greatly help me in the process of testing Apricate the help -
Challenges Encountered in Retrieving Information Using Token Authentication in a Django REST API
Challenges Encountered in Retrieving Information Using Token Authentication in a Django REST API Experiencing Difficulty Performing GET and POST Operations with Token Authentication for Data Retrieval This is my views. from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from .models import Student from .serlizer import StudentSerlilizer from rest_framework import status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated class StudentInfo(APIView): authentication_classes = [TokenAuthentication] # Apply TokenAuthentication permission_classes = [IsAuthenticated] # Apply IsAuthenticatedOrReadOnly permission def get(self, request, format=None): stu = Student.objects.all() serlizer = StudentSerlilizer(stu,many=True) return Response(serlizer.data) def post(self,request,format=None): request_data = request.data serlizer = StudentSerlilizer(data=request_data) if serlizer.is_valid(): serlizer.save() msg = {'msg':'Your data has been saved'} return Response(msg) msg = {'msg':serlizer.errors} return Response(msg,status.HTTP_400_BAD_REQUEST) And this is my urls:- from django.urls import path from . import views # from rest_framework.authtoken.views import obtain_auth_token from rest_framework_simplejwt.views import TokenObtainPairView,TokenRefreshView,TokenVerifyView urlpatterns = [ # path('authtoken/',obtain_auth_token), path('gettoken/',TokenObtainPairView.as_view(),name="get_token"), path('refreshtoken/',TokenRefreshView.as_view(),name="refresh_token"), path('verifytoken/',TokenVerifyView.as_view(),name="verify_token"), path('studentinfo/',views.StudentInfo.as_view(),name="studentlist"), path('studentinfo/<int:pk>/',views.StudentRUD.as_view(),name="StudentRUD") ] When i tried to get the values by using Tokenauth, i'm getting this error: { "detail": "Authentication credentials were not provided." } This is how i tried to Get the values:- http GET http://127.0.0.1:8000/studentinfo/ 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjk1MzYxMTk5LCJpYXQiOjE2OTUzNjA4OTksImp0aSI6ImY1ODY1MWE5NjMwNTRhMDA4MzA6NTFmZTJmMzU1MTgwIiwidXNlcl9pZCI6MX0.GmlHfKR59s6SUDEI_ZHardNDDH7T_lEWYJlIBxc3LmI' HTTP/1.1 401 Unauthorized Allow: GET, POST, HEAD, OPTIONS Content-Length: 58 Content-Type: application/json Cross-Origin-Opener-Policy: same-origin Date: Fri, … -
Using models package to manage multiple models in Django but migration cannot be generated
I followed the steps in the documentation but couldn't succeed. What do I need to do to generate migration files? I try to put all models in models.py and it can be generated apartment/models/__init__.py: from .water_bill import WaterBill from .electricity_bill import ElectricityBill Directory Structure apartment/ views.py __init__.py models/ __init__.py electricity_bill.py water_bill.py Script executed python manage.py makemigrations apartment then show “No changes detected in app 'apartment'" -
how to resolve import error for package utils.stellar_utils in python django
Am recieving the follwong error #views.py import "utils.stellar_utils " could not be resolved but the i have just installed the lest version of the sdk here is a snap short of my view.py from stellar_sdk import Keypair from django.conf import settings from utils.stellar_utils import server def send_transaction(request): # your send transaction logic here source_keypair = Keypair.from_secret(request.user.secret_key) destination_public_key = request.POST['destination_public_key'] amount = request.POST['amount'] asset = Asset.native() transaction = ( TransactionBuilder( source_account=server.load_account(source_keypair.public_key), network_passphrase=settings.STELLAR_NETWORK_PASSPHRASE, base_fee=server.fetch_base_fee(), ) .append_payment_op(destination_public_key, amount, asset) .set_timeout(30) .build() ) transaction.sign(source_keypair) response = server.submit_transaction(transaction) and below is my requirements.txt aiohttp==3.8.5 aiohttp-sse-client==0.2.1 aiosignal==1.3.1 asgiref==3.7.2 async-timeout==4.0.3 attrs==23.1.0 certifi==2023.7.22 cffi==1.15.1 charset-normalizer==3.2.0 Django==4.2.4 frozenlist==1.4.0 idna==3.4 mnemonic==0.20 multidict==6.0.4 psycopg2-binary==2.9.7 pycparser==2.21 PyNaCl==1.5.0 requests==2.31.0 six==1.16.0 sqlparse==0.4.4 stellar-base-sseclient==0.0.21 stellar-sdk==8.2.1 toml==0.10.2 typeguard==2.13.3 tzdata==2023.3 urllib3==2.0.5 yarl==1.9.2 i am using the latest version os stella skk with all the dependencies installed -
How to handle mysql inactivity error in thread
I'm using MySQL in Django project, MYSQL and the server is running smoothly in normal site operation, but some operations are running in the thread. In thread after inactivity of 4-5hours it show error like: django.db.utils.OperationalError: (4031, 'The client was disconnected by the server because of inactivity. See wait_timeout and interactive_timeout for configuring this behavior.') I tried different ways to reconnect and handle this error but not work, I'm using django ORM for db operations and db config is: db_config = { 'default': { 'ENGINE': DB_ENGINE, 'NAME': DB_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASSWORD, 'HOST': DB_HOST, 'PORT': DB_PORT, 'CONN_MAX_AGE': 24*60*60, 'POOL_OPTIONS': { 'POOL_SIZE': 10, 'MAX_OVERFLOW': 10, 'RECYCLE': -1 } } } Here, db engin is dj_db_conn_pool.backends.mysql used packages: mysql-connector-python==8.0.27 mysqlclient apt-get install libmysqlclient-dev -
How to optimize nested loop query of models with one-to-many relationship
I have two models with a one-to-many relationship. There are several objects of each model class in the database. I created a custom queryset that iterates over all parent objects and all child objects then loads them into a dictionary that is then used as the queryset. My question is how can I optimize my nested_query_loop function to hit the database less times? I tried incorporating select_related() and prefetch_related() but could never get it to work since I need to query it as a backward relationship in order to get each child object to be with its parent object. Second part of the question: I tried making the function reusable by creating parent_object and child_object arguments, but this did not work due to the fact that I have to use the ObjectName_set() method, which requires the objects name to be lower cased. Also the fact that ObjectName_set() has an underscore made it so child_object_set() and even ChildObject_set() was not recognized and threw an error. In my case the child objects model name is first letter upper case. So my question is: is there any way to manipulate the models name inside the function to be all lower cased? or is … -
I got error on apache2 server django application Failed to proxy response from daemon
The website works fine only for 1-2 requests, after which it starts loading endlessly and if I wait for some time I get an Internal Server Error. After this i reload the server sudo systemctl reload apache2 website works for 1 request and i got same problem again (When i use runserver 0.0.0.0:8000 it works fine) I use django application on Ubuntu 22.04 Using apache2 and libapache2-mod-wsgi-py3 Libapache version is: libapache2-mod-wsgi-py3/jammy-updates,jammy-security,now 4.9.0-1ubuntu0.1 amd64 [installed] Python version 3.10.12 My apache file conf etc/apache2/apache.conf (i added here only Servername and LimitRequestFieldSize) ServerName caspian-bavarians.com DefaultRuntimeDir ${APACHE_RUN_DIR} PidFile ${APACHE_PID_FILE} Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 5 User ${APACHE_RUN_USER} Group ${APACHE_RUN_GROUP} HostnameLookups Off ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn IncludeOptional mods-enabled/*.load IncludeOptional mods-enabled/*.conf Include ports.conf <Directory /> Options FollowSymLinks AllowOverride None Require all denied </Directory> <Directory /usr/share> AllowOverride None Require all granted </Directory> <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> AccessFileName .htaccess <FilesMatch "^\.ht"> Require all denied </FilesMatch> LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %O" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent IncludeOptional conf-enabled/*.conf IncludeOptional sites-enabled/*.conf … -
SpotDL on Django
I am trying to create a Django project on SpotDL. Here's my files: --urls.py urlpatterns = [ path('admins/', admin.site.urls), path('spdl/', views.spdl), ] --views.py def spdl(request): import spotdl spotify_url = "https://open.spotify.com/track/2Cd9iWfcOpGDHLz6tVA3G4"; subprocess.run(['spotdl', spotify_url] , check=True) return HttpResponse("downloaded") It successfully downloads the track on my PC. But, I want to customize it a little bit. I want to set the --bitrate on views.py file during the spotdl call. I tried this line but failed: (got via ChatGPT) subprocess.run(['spotdl', '--bitrate', '128', spotify_url], check=True) How can I pass other commands to SpotDL like --bitrate or --cookie-file cookies.txt? -
Original Django template with side Jinja2 template in same template
I have read This document. My Django version: 4.2.5 Jinja2 version: 3.1.2 I need using Jinja2 for using set (manipulating variables) with Django templates. (For working with query sets) My settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.media', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I need rendering documents originally with Django templates, side version with Jinja2. That both tag and codes are work. How can set my settings.py and others, getting ready my project have this ability? -
template expectations when two models within same Django model file
I have two different (related) model classes within a Django tennis ladder app: Ladder and Player. For the corresponding views file, I include both sets of corresponding class-based views within the same file. And I also include all the urls in the same file as well. These look as follows: from django.urls import path from .views import HomePageView, PlayerListView, PlayerDetailView, \ PlayerEditView, PlayerCreateView, PlayerDeleteView, \ LadderListView, LadderDetailView, LadderDeleteView urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('players/', PlayerListView.as_view(), name='players'), path('player/detail/<int:pk>/', PlayerDetailView.as_view(), name='player_detail'), path('player/edit/<int:pk>/', PlayerEditView.as_view(), name='player_edit'), path('player/create/', PlayerCreateView.as_view(), name='player_create'), path('player/delete/<int:pk>/', PlayerDeleteView.as_view(), name='player_delete'), path('ladder_history/', LadderListView.as_view(), name = 'ladder_history'), path('ladder/detail/<int:pk>/', LadderDetailView.as_view(), name = 'ladder_detail'), path('ladder/delete/<int:pk>/', LadderDeleteView.as_view(), name='ladder_delete'), ] Within the project urls I include the path to this urls file as follows. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path('', include('players.urls')), path('', include('matches.urls')), path('accounts/', include('accounts.urls')), ] Here's the problem. When I click on a button to pull up the ladder_history, Django seems to expect the template to located at TemplateDoesNotExist at /ladder_history/ players/ladder_list.html Request Method: GET Request URL: http://127.0.0.1:8000/ladder_history/ Django Version: 4.2.5 Exception Type: TemplateDoesNotExist Exception Value: players/ladder_list.html I am totally mystified. I do not have a 'ladder_list.html', but rather 'ladder_history.html', as I specify in the … -
Waiting for request django
I need to send a request from my React client to the Django server. Processing this request may take about 30 seconds, due to the calculations in the function. What is the best approach to handle this case? Currently, I opt for celery+redis or WebSockets, but maybe there is a simpler approach? -
Why CORS error is rising only for search endpoint?
I have an app running on Django, React, and Elasticsearch. The react app is able to communicate with the django rest API normally in the endpoint http://localhost:8000/api/results/. But this endpoint renders the entire database. I use ES to create an endpoint that receives a query. The endpoint http://localhost:8000/api/results/q=query works correctly in the browser. However, when I tried to render it in the frontend, it returned a CORS error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/results/q=education. (Reason: CORS request did not succeed). Status code: (null). For development purposes, I allow CORS access to all addresses in my settings.py file: CORS_ORIGIN_ALLOW_ALL = True How is it possible to access http://localhost:8000/api/results/ from react and not access http://localhost:8000/api/results/q=query? P.S.:For completeness, here is my react code: export default function Body() { const location = useLocation(); const searchQuery = new URLSearchParams(location.search).get("q"); const [offices, setOffices] = useState([]); const office = true; useEffect(function () { async function fetchData() { const baseUrl = import.meta.env.VITE_API_URL; let apiUrl = `${baseUrl}/results/`; if (searchQuery) { apiUrl += `q=${encodeURIComponent(searchQuery)}`; } console.log(apiUrl); const res = await fetch(apiUrl); const data = await res.json(); setOffices(data); } fetchData(); }, [searchQuery]); -
Rebuild mod_wsgi if additional packages are added to venv
Do Django mod_wsgi need to be rebuilt under Apache if additional packages are added to venv? After installing additional packages in python venv, Apache server crashed, it says that the packages are not found, although they are installed in venv. I use python==3.10, Django==4.2. -
"Cannot find reference 'TextFields' in '__init__.py'
I tried importing models from django.db . At first PyCharm could not recognize the django.db although I had already installed it using cmd so i installed it again in pycharm but I am still getting the error "Cannot find reference 'TextFields' in 'init.py' " Tried creating a new app in my project -
DJANGO REST API - How do I restrict user access to API?
So I’ve been putting together a REST API using William Vincent’s REST API’s with Django book. I have everything up and going according to the book but I’m a bit of a noob so I need some clarification from the pros. How can I restrict a user without a token from seeing certain information within my API? Created user with Token: i added authentication_classes = [TokenAuthentication] to class UserList thinking if a user is logged in with a token that logged in user would be able to access that information of my api but I get the below: When I remove authentication_classes = [TokenAuthentication], I get the below. All users are able to see my API and I don’t want that, I only want users with a Token to view my api. Any help is gladly appreciated! Thanks! Code below # api/views.py from django.contrib.auth import get_user_model from rest_framework import generics, permissions from rest_framework.authentication import TokenAuthentication from .serializers import UserSerializer # Display List View - User class UserList(generics.ListAPIView): queryset = get_user_model().objects.all() serializer_class = UserSerializer permission_classes = (permissions.IsAuthenticated,) authentication_classes = [TokenAuthentication] # api/serializers.py from django.contrib.auth import get_user_model from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields =('id', 'username', 'email',) … -
Capture and edit site url and use value in html django
Want to get the site url and parse the path down to the string input and then validate that string is in a django model table. What I have done so far works in that it will display the string entered, but do not know how to then use it to compare what is in the customuser model alias_name field. If it is in the table, it should render the from in the template, if not, then it should render Sorry not found. FYI - I am new to this and have done my due deligence it resarching this. app/urls.py path('signup/str:alias_name/', SignUpView.as_view(), name='accounts/signup.html'), This allows any string to be put in here and the page renders. app/views.py class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy("login") template_name = "registration/signup.html" model = CustomUserCreationForm app/forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ( "first_name", "last_name", "email", "cell", "username", 'password1', 'password2', 'alias_name', 'org', ) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ( "first_name", "last_name", "username", "email", "cell", ) template <!DOCTYPE html> <html> <body> {% extends "base.html" %} {% block title %}Sign Up{% endblock %} {% block content %} <h2>Sign Up</h2> <p id="alias"></p> <script> document.getElementById("alias").innerText = window.location.pathname.toString().replace('/accounts/signup/', '').replace('/', ''); </script> <h1>Your … -
How to make Django respect locale when accessing localflavor?
I'm trying to apply multi-language support to a Django application, and I have the basic configuration working so I can set a language session key and automatically pull the correct translations for the each gettext call around all my field labels. However, I have some Ajax calls that populate fields for country/state/province names, pulling data from the django-localflavor package, which includes full translation support. However, when I return, say, localflavor.jp.jp_prefectures.JP_PREFECTURES in my JSON response, even though my language session key is set to Japanese, and the values in that dictionary are wrapped with gettext, the values returned are in English, not Japanese. My Ajax view looks something like: from localflavor.jp.jp_prefectures import JP_PREFECTURES def get_country_states(request): lang = request.session.get('l', 'en') code = request.GET.get('code') if code == 'jp': states = {k: str(v) for k, v in JP_PREFECTURES} elif code == ... handle other cases return HttpResponse(json.dumps({'states': states})) How do I ensure str(v) renders the correct translated value based on the current language l session setting? I thought this happened automatically? Even though the values in JP_PREFECTURES are gettext instances, if I try and return them directly in the JSON response, I get the error: Object of type __proxy__ is not JSON serializable -
Django left join with filtered relation in QuerySet for ListView
I am a Django/Python novice. I am developing a website to help me manage a small golf society. A major function of the website is to enable members to view and book their place on upcoming events. The EventListview will display details for each event, including the venue(s) used by each event. It will also allow the member to Make/View/Modify/Cancel a booking for each event. All of this functionality is working apart from displaying the venue(s) for each event in the EventListView. members.models.py class Member(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) handicap = models.IntegerField(null=True, blank=True) etc ........ events.models.py class Venue(models.Model): name = models.CharField(max_length=64) description = models.TextField(max_length=256, null=True, blank=True) etc ........ class Event(models.Model): name = models.CharField(max_length=64) details = models.CharField(max_length=256) start = models.DateField(null=True, blank=True) finish = models.DateField(null=True, blank=True) etc ........ def get_venues(self): return mark_safe("<br />" . join([x.venue.__str__() for x in self.venue.all()])) class Event_Venue(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='venue') venue = models.ForeignKey(Venue, on_delete=models.CASCADE, related_name='event') etc ........ class Member_Event(models.Model): member = models.ForeignKey('members.Member', on_delete=models.CASCADE, related_name='booking') event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='booking') etc ........ events.views.py class EventListView(LoginRequiredMixin, ListView): model = Event context_object_name = 'event_list' paginate_by = 8 template = 'events/event_list.html' def get_queryset(self): return Event.objects.annotate(booked=FilteredRelation('booking', condition=Q(booking__member=self.request.user.member))).values('id', 'name', 'details', 'start', 'finish', 'currency', 'price', 'status', 'booked__member') event_list.html . . . {% if … -
Django All-Auth with Djongo (PyMongo)
I've created a Django project that uses the Djongo plugin to connect to a MongoDB instance. All works well with Djongo, however, now that I am trying to implement all-auth, there are some problems. Upon logging in (using the default all-auth process and clicking Google), I get this DatabaseError. It doesn't really give any exception, but my theory is that I need to create a User model that uses the Djongo model, which I've been unsuccessful in doing. Has anybody done a similar setup that can help? Run this branch here (directions in README.md, however you will need a google OAUTH credential) to replicate the problem https://github.com/bens-schreiber/pushapp-2023/tree/schreiber/all-auth/backend -
I can't prepare multiple databases in Django (sqlite3)
There is a problem which I can't understand how that happens. First let me clear what do I want: Use a database called sol_data.sqlite3 for two models: SolModel1, SolModel2 (These models defined in an app called sol_app) Use a database called db.sqlite3 for any other models like always (Django built-in models and other apps) It's obvious db.sqlite3 should not include SolModel1 and 2. and sol_data.sqlite3 should only include SolModel1 and 2 tables. But when I migrate, both tables have all django models, and sol_data.sqlite3 have SolModel1 and 2 addition to them. I'm confused. (I read the docs: https://docs.djangoproject.com/en/4.2/topics/db/multi-db) My code settings.py ... # other settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, "sol_data_db": { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'sol_data_db.sqlite3', } } DATABASE_ROUTERS = ["sol_app.dbrouters.SolDataRouter"] ... # other settings sol_app/dbrouters.py class SolDataRouter: def db_for_read(self, model, **hints): if model._meta.app_label == "sol_app": return "sol_data_db" return None def db_for_write(self, model, **hints): if model._meta.app_label == "sol_app": return "sol_data_db" return None def allow_relation(self, obj1, obj2, **hints): if (obj1._meta.app_label == "sol_app" and obj2._meta.app_label == "sol_app"): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == "sol_app": return db == "sol_data_db" else: return None my terminal ➜ python manage.py … -
The view App.views.login_view didn't return an HttpResponse object. It returned None instead
def login_view(request): if request.method == 'POST': form = AuthenticationForm(request.POST) if form.is_valid(): user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password']) if user != None: auth_login(request, user) return redirect('home') else: return redirect('login') else: form = AuthenticationForm() context = { 'form': form, } return render(request, "login.html", context) Its not redirecting me 404.html page or home.html page for that matter this the error i am getting I using "auth_user" database also my urls are configured properly Request Method: POST Request URL: http://127.0.0.1:8000/login/ Django Version: 4.2.5 Exception Type: ValueError Exception Value: The view App.views.login_view didn't return an HttpResponse object. It returned None instead. -
I wrote the first project from the Django site, it does not issue an error, but when I go to the browser, it only shows the picture of the rocket
enter image description here I imported the code from the first Django site project and expected the Django function codes to run in the browser, but they all show rocket images. Do I need to install a specific item or program? -
unwanted line break in flex box
i have a flex container 'elements' (direction column) and im trying to add items to it using js script: // Generate and append the inner elements for (var j = 0; j < 3; j++) { var innerDiv = document.createElement('div'); innerDiv.textContent = '3/12'; //this works elements.appendChild(innerDiv); } when the textContent is normal there is no problem, i get 3 lines no matter how long the text is. but when i try to enter (as it seems) 2 specific characters together one after another like innerDiv.textContent = '[i][j]'; //i get [i] and [j] in seperated lines innerDiv.textContent = '1/√5'; //i get 1/ and √5 in seperated lines and end up with twice the rows. i tried to make sure its a string, didnt work. also it doesnt have anything to do with the style i checked. thanks for the help! -
Filtering in the dictionary list for the jsonfield in Django
I have a django model that uses postgres json column. class ClassName(models.Model): data=JsonField(default=dict,blank=True,null=True,) This is the schema in the json field. { "name": "foo", "thing":[ { "id": "1", "key": "hello" }, { "id": "2", "key": "world" } ] } Is it possible to search against one key value in the list of dictionaries using ILIKE (icontains) operator? ClassName.objects.filter(data__thing__key__icontains="wo") Maybe someone has faced this problem? I will be glad of any considerations ClassName.objects.filter(data__thing__contains=[{'key':'world'}]) - works (but only contains) ClassName.objects.filter(data__thing__1__key__icontains='wo') - works (but only with the indication of the element) -
Problem with dockerizing a Django project with Celery and RabbitMQ
I am trying to dockerize my Django project with Celery and RabbitMQ. I have a Docker Compose file, but I am having trouble getting it to work. Here is my Docker Compose file: services: rabbitmq: image: rabbitmq:latest networks: - main ports: - "5672:5672" restart: always environment: - RABBITMQ_DEFAULT_USER=guest - RABBITMQ_DEFAULT_PASS=guest celery_worker: image: python:3.10 command: celery -A zwitter worker -l INFO build: context: . depends_on: - app - rabbitmq environment: - CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672/ networks: - main restart: always redis: image: redis:latest ports: - "6379:6379" volumes: - cache:/data command: redis-server --save 60 1 restart: always app: image: python:3.10 build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/src/ ports: - "8000:8000" networks: main: volumes: cache: When I try to start the Docker Compose containers, everything works fine and the containers are all up. But when any celery task is about to run in my django project, I get the following error: [Errno -3] Temporary failure in name resolution I have tried all of the following, but the problem still persists: Making sure that the RabbitMQ server is running and accessible. Making sure that the Celery worker is configured to connect to the correct …