Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I make database calls asynchronous inside Telegram bot?
I have a Django app that runs a Telegram chatbot script as a command. I start the Django app with python manage.py runserver. I start the telegram client with python manage.py bot. I want to list the entries from the Animal table within the async method that is called when a user types "/animals" in the telegram chat. My code works if I use a hard-coded list or dictionary as a data source. However, I'm not able to get the ORM call to work in async mode. File structure: |Accounts--------------------- |------| models.py------------ |Main------------------------- |------| Management----------- |---------------| Commands---- |-----------------------bot.py Animal model: class Animal(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) I removed a lot from the file, leaving only the relevant bits. bot.py # removed unrelated imports from asgiref.sync import sync_to_async from accounts.models import Animal class Command(BaseCommand): help = "Starts the telegram bot." # assume that the token is correct TOKEN = "abc123" def handle(self, *args, **options): async def get_animals(): await Animal.objects.all() async def animals_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: async_db_results = get_animals() message = "" counter = 0 for animal in async_db_results: message += animal.name + "\n" counter += 1 await update.message.reply_text(message) application = Application.builder().token(TOKEN).build() application.add_handler(CommandHandler("animals", animals_command)) … -
how to cancel a xhr request
i am trying to upload a file to django server backend.i added a progress bar by using javascript,xhr and ajax method also i added a cancel button to cancel the upload the progress bar is working properly but the cancel is not working. i used xhr.abort() method to cancel the xhr request,when i clicking the cancel button it stops the progress and again starts to upload from zero.(the cancel button seems like stops the progress but the file again starts to upload. -
Issue with S3 Uploads in Dockerized Django App on ECS
I'm facing an issue with S3 uploads in my Dockerized Django application running on AWS ECS. The setup includes RDS and S3, and I've successfully tested file uploads locally using docker run and Postman. However, when I create a task definition, launch an ECS EC2 cluster with a load balancer and a target group, and attempt to upload a file to S3, I'm encountering a 504 Gateway Timeout error. In the logs, I see the message 'Loading s3:s3,' and the service breaks, then reloads. for IAM i add S3FullAccess to all IAM related to my ecs in security groups i allow all traffic (inbound, outbound) in security groups i allow all traffic (inbound, outbound) Added the AmazonS3FullAccess policy to the ecsTaskExecutionRole IAM role associated with ECS tasks. Confirmed IAM role changes have propagated. Checked the trust relationship of the ecsTaskExecutionRole to allow ECS to assume the role. -
How can I run swagger in docker container with Python 3.12 and Django?
i've docker file and docker-compose for my api in Python. I want when the container runs, it starts the api with swagger. I tried with the own swagger and with the drf-yasg but i can't run the container, can anyone help me? Now, I'm trying with the drf-yasg but this error pops up: Creating network "api-cardiotech_default" with the default driver Creating api-cardiotech ... done Creating django ... done Attaching to django, api-cardiotech django exited with code 0 api-cardiotech | Watching for file changes with StatReloader api-cardiotech | Exception in thread django-main-thread: api-cardiotech | Traceback (most recent call last): api-cardiotech | File "/usr/local/lib/python3.11/threading.py", line 1045, in _bootstrap_inner api-cardiotech | self.run() api-cardiotech | File "/usr/local/lib/python3.11/threading.py", line 982, in run api-cardiotech | self._target(*self._args, **self._kwargs) api-cardiotech | File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper api-cardiotech | fn(*args, **kwargs) api-cardiotech | File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run api-cardiotech | autoreload.raise_last_exception() api-cardiotech | File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception api-cardiotech | raise _exception[1] api-cardiotech | File "/usr/local/lib/python3.11/site-packages/django/core/management/init.py", line 394, in execute api-cardiotech | autoreload.check_errors(django.setup)() api-cardiotech | File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper api-cardiotech | fn(*args, **kwargs) api-cardiotech | File "/usr/local/lib/python3.11/site-packages/django/init.py", line 24, in setup api-cardiotech | apps.populate(settings.INSTALLED_APPS) api-cardiotech | File "/usr/local/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate api-cardiotech | … -
SASS/SCSS django
PHOTO - show mistake(https://i.stack.imgur.com/wXCf5.png) Why got red underline (photo) as some problem in code, is there are some mistake? But it work properly... And the same question to sass in link... What to do for remove this "mistake". {% load sass_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="{% sass_src 'css/main.scss' %}" rel="stylesheet" type="text/css"/> <title>Django Sass</title> </head> <body> <h1>WORK</h1> </body> <html> -
name is not passing through a function to another function in django
i am trying to pass a variable called name to pass to a function which is present in another function. I want to pass the variable name to the function plane and check if the values are matching with any of the names in my database. my views.py is from django.shortcuts import render,redirect from django.contrib.auth.forms import AuthenticationForm from .models import Logs,Plane from .forms import Login from django.contrib import messages from django.contrib.auth import authenticate, login ,logout from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from django.http import HttpResponse import json from django.http import JsonResponse # Create your views here. def loger(request): global name formy = AuthenticationForm() c=[] a=Logs.objects.all() if request.method == 'POST': formy = AuthenticationForm(data=request.POST) name=request.POST.get('username') password = request.POST.get('password') obj=Logs() obj.get_special_combination_value for b in a: if name == b.name and password == b.password: return redirect('ticket',pk=b.id) return render(request,'project/loger.html',{'formy':formy,'a':a}) def homepage(request): form=Login() if request.method=='POST': form=Login(request.POST) if form.is_valid(): user=form.save() plane_instance = Plane(name=user.name, password=user.password) plane_instance.save() return redirect('ticket',pk=user.pk) return render(request,'project/homepage.html',{'form':form}) def ticket(request,pk): tic=Logs.objects.get(id=pk) return render(request,'project/ticket.html',{'tic':tic}) def forgor(request): a=Logs.objects.all() if request.method=='POST': username=request.POST.get('name') password=request.POST.get('password') obj=Logs() obj.get_special_combination_value Logs.objects.filter(name=username).update(password=password) return redirect('homepage') return render(request,'project/forgor.html',{'a':a}) def plane(request): print(name) a=Logs.objects.all() b=Plane.objects.all() for c in b: if name==c.name: log_instance=Plane.objects.get(id=c.id) plane_instance=Plane.objects.get(id=c.id) for d in a: if name==d.name: plane_instance1=Logs.objects.get(id=d.id) if request.method == 'POST': checkbox_dict_json = request.POST.get('checkboxDict') … -
Python Dramatiq - how can I get environment variables?
I'm trying to get environment variables using dramatiq: @dramatiq.actor def create_instance(): subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"] credential = DefaultAzureCredential() But I get this error: KeyError: 'AZURE_SUBSCRIPTION_ID' I think this means dramatiq can't get my environment variables. I tried to get them before calling the function and passing them as arguments: subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"] credential = DefaultAzureCredential() create_instance.send(subscription_id, credential) @dramatiq.actor def create_instance(subscription_id, credential): ... But the problem is the credential can't be passed as an argument: Object of type DefaultAzureCredential is not JSON serializable Is there any solution? Thanks -
Django/Wagtail Language Redirection not working for 3 letter language code (kri)
I have set up Wagtail (latest) for multi-language. Works fine with Portuguese (pt), but I'm trying to work for Krio, which has a 3 character language code: kri. I have had to add Krio manally to LANG_INFO etc, and this works fine in the Wagtail UI, allowing me to set up alternate homepages for pt and kri, but when it comes to do the language redirecting, it fails to redirect to the kri translation. Is it possible I have missed a setting? Can the redirection logic handle 3 letter codes? My language settings: WAGTAIL_I18N_ENABLED = True USE_L10N = True LANGUAGES = [ ('en-GB', "English (Great Britain)"), ('en-US', "English (United States)"), ('en-CA', "English (Canada)"), ('pt', "Portuguese"), ('kri', "Krio (Sierra Leone Creole)"), ] WAGTAIL_CONTENT_LANGUAGES = [ ('en-GB', "English (British)"), ('kri', "Krio (Sierra Leone Creole)"), ('pt', "Portuguese"), ] EXTRA_LANG_INFO = { "kri" : { 'bidi': False, 'code': 'kri', 'name': 'Sierra Leonean Creole (Krio)', 'name_local': 'Krio', }, } LANG_INFO = dict(django.conf.locale.LANG_INFO, **EXTRA_LANG_INFO) django.conf.locale.LANG_INFO = LANG_INFO My middleware: MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "allauth.account.middleware.AccountMiddleware", "wagtail.contrib.redirects.middleware.RedirectMiddleware", ] My urls patterns: urlpatterns = [ # path('django-admin/', admin.site.urls), path('cms/', include(wagtailadmin_urls)), path('documents/', include(wagtaildocs_urls)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Translatable URLs # These will … -
Problem accessing server through .onion domain
I tried to access a django server I was running on my virtual machine (Ubuntu 22.04.3) through an onion domain from my host OS(Windows 11) First I installed tor and edited my torrc file and added these lines: HiddenServiceDir /var/lib/tor/hidden_service/ HiddenServicePort 8002 127.0.0.1:8002 then I saw my host name in /var/lib/tor/hidden_service/hostname. root@soroush-VirtualBox:/home/soroush/Desktop/dw# cat /var/lib/tor/hidden_service/hostname jn46lvmv4uu7bjfveoax.............rxv6ljid.onion then I started a django project and edited settings.py to allow all host names ALLOWED_HOSTS = ['*'] then I started a django server on my 8002 port python manage.py runserver 127.0.0.1:8002 then I tried to access my django server using the onion link. I copied the url in my tor browser on my host OS. but nothing loaded. I didn't even get any requests in my django server. I even tried using tor browser on my phone with a different network but that didn't work neither. the tor service is running and my django server works ok when I use my locan IP (127.0.0.1:8002). but when I try to access it through onion domain I can't. what am I doing wrong? I tried to access my django server through an onion domain but I couldn't -
Django Class Based View: Deny access to future dates unless logged in
I have a Promotion model containing a published_date field. I would like to restrict access to future promotions to logged in users who are 'previewing' their promotion. class Promotion(models.Model): title = models.CharField(max_length=100, blank=False, null=False) ... promotion_date = models.DateField(blank=False, null=True) At the moment I'm running a simple Class Based DetailView: class PromotionDetailView(generic.DetailView): model = Promotion context_object_name = 'book' template_name = 'PromoManager/book_detail.html' But I am unsure how or when to intercept this request and add the condition for non logged in users to redirect if promotion_date is greater than today. I currently have simple_tag which returns a bootstrap alert highlighting future promotions but this is purely visual. in_the_future = timezone.now().date() if hasattr(book, 'promotion_date') and book.promotion_date > in_the_future: return ...appropriate message... If I was doing it via Function Based Views I would apprach it with an if statement combined with a redirect. I considered the same approach via DetailView/TemplateView and get_context_data but this doesn't feel right. How can I best intercept the request and redirect the page for non-logged in users if the promotion_date is in the future? -
Django BaseDataTableView - filter_queryset method not work
I am using BaseDatatableView and DataTable jquery. I've already written several views for BaseDatatableView and there were no problems until I had to override the 'prepare_results' and 'render_column' methods. I need to present the results of instance methods in a table, so I overwrite the methods of the BaseDatatableView class. This is my code in views.py class MyModelDatatable(BaseDatatableView): model = MyModel columns = ['field1', 'field2', 'id'] columns_searched = [col for col in columns if col != 'id'] def get_initial_queryset(self): return self.model.objects.all() def filter_queryset(self, qs): print('test') # not displayed search_text = self.request.GET.get('search[value]', None) if search_text: search_terms = search_text.split() query = Q() for col in self.columns_searched: or_conditions = Q() for term in search_terms: or_conditions |= Q(**{f'{col}__icontains': term}) query |= or_conditions qs = qs.filter(query) return qs def prepare_results(self, qs): data = [] for item in qs: item_str = str(item) data.append({ 'field1': item_str, 'field2': item.field2, 'id': item.id }) return data def render_column(self, row, column): if column == 'field2': return row.date.strftime('%Y-%m-%d') return super(OrderDatatable, self).render_column(row, column) def get(self, request, *args, **kwargs): return self.get_json_response() def get_json_response(self): draw = int(self.request.GET.get('draw', 1)) total_records = self.get_initial_queryset().count() total_display_records = total_records start = int(self.request.GET.get('start', 0)) length = int(self.request.GET.get('length', 10)) end = start + length data = self.prepare_results(self.get_initial_queryset()[start:end]) response = { 'draw': draw, … -
SSL Certification Requirements Safety Question
I am using Heroku and Redis in a production environment built with Django and have been getting errors with SSL. At first I had this issue: A rediss:// URL must have parameter ssl_cert_reqs and this must be set to CERT_REQUIRED, CERT_OPTIONAL, or CERT_NONE I then tried adding ?ssl_cert_reqs=CERT_REQUIRED To my CELERY_RESULT_BACKEND Which then returned this error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain I then changed the ?ssl_cert_reqs to equal CERT_NONE and this has solved all issues completely. My question is if this fix is safe from any attacks or if this has completely got rid of the SSL certificates. I have read on a few pages that people have used this to fix their issue but I am working on a production app and do not want to compromise on safety. Any help would be greatly appreciated. Thank you, Liam -
Python issue with redis hostname not resolved in docker
I seem to have issues while trying to setup redis instance via python/django. I have a lot of containers running in docker-compose and while other containers are able to connect properly, when trying with Django I get: Step 11/16 : RUN python3 /home/allianceserver/myauth/manage.py collectstatic ---> Running in 749d9931dadb [30/Oct/2023 08:59:47] INFO [allianceauth.eveonline.providers:181] ESI client will be loaded on-demand [30/Oct/2023 08:59:47] ERROR [allianceauth.authentication.task_statistics.helpers:44] Failed to establish a connection with Redis. This EventSeries object is disabled. Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 264, in connect sock = self.retry.call_with_retry( File "/usr/local/lib/python3.9/site-packages/redis/retry.py", line 46, in call_with_retry return do() File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 265, in <lambda> lambda: self._connect(), lambda error: self.disconnect(error) File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 595, in _connect for res in socket.getaddrinfo( File "/usr/local/lib/python3.9/socket.py", line 954, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -2] Name or service not known During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/allianceauth/authentication/task_statistics/helpers.py", line 41, in get_redis_client_or_stub if not redis.ping(): File "/usr/local/lib/python3.9/site-packages/redis/commands/core.py", line 1216, in ping return self.execute_command("PING", **kwargs) File "/usr/local/lib/python3.9/site-packages/redis/client.py", line 533, in execute_command conn = self.connection or pool.get_connection(command_name, **options) File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 1086, in get_connection connection.connect() File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 270, in connect raise ConnectionError(self._error_message(e)) redis.exceptions.ConnectionError: … -
Django REST framework: get last related object
I am trying to get the last related object in a Django REST framework view. With the current implementation I am getting this error - but I am not sure if this is the correct approach: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer. I have this two models (little bit cleaned up): class Device(models.Model): name = models.TextField() def get_last_status(self): return self.status.last() class DeviceStatus(models.Model): class eDeviceStatus(models.TextChoices): OFFLINE = 'F', _('Offline') ONLINE = 'L', _('Online') device = models.ForeignKey(Device, related_name='status', on_delete=models.CASCADE) status = models.CharField(max_length=1, choices=eDeviceStatus.choices, default=eDeviceStatus.OFFLINE) last_update = models.DateTimeField() with this Device view: class DeviceViewSet(ModelViewSet): serializer_class = DeviceSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): return Device.objects.filter(owner=self.request.user) def perform_create(self, serializer): serializer.save(owner=self.request.user) and this Device serializer: class DeviceSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') last_status = serializers.SerializerMethodField() class Meta: model = Device fields = ['url', 'id', 'name', 'last_status'] def get_last_status(self, obj): s = obj.get_last_status() serializer = DeviceStatusSerializer(s) return serializer.data I would like to have in my api the last status (field: last_status) from the DB. But I am failing to have it correctly implemented. How can I have the last_status correctly set? -
Specify lookup_url_kwarg in the nested route using drf-nested-routers
Using drf-nested-routers we have implemented many nested routes that go two levels in depth. Just as in the documented examples: /clients/ /clients/{pk}/ /clients/{client_pk}/maildrops/ /clients/{client_pk}/maildrops/{pk}/ /clients/{client_pk}/maildrops/{maildrop_pk}/recipients/ /clients/{client_pk}/maildrops/{maildrop_pk}/recipients/{pk}/ However, I don't like the inconsistency in the 4th line. How can I make the lookup_url_kwarg be maildrop_pk there too? /clients/{client_pk}/maildrops/{maildrop_pk}/ If I set the lookup_url_kwarg in the MailDropViewSet to maildrop_pk, then it appears correctly in this route, but the nested routes for MailRecipient become: /clients/{client_pk}/maildrops/{maildrop_maildrop_pk}/recipients/ /clients/{client_pk}/maildrops/{maildrop_maildrop_pk}/recipients/{pk}/ I want to have a consistent naming across all nested routes. -
DRF ViewSet always returns HTTP 200
I'm new to DRF. This is my ViewSet: class AccountViewSet(viewsets.ViewSet): def list(self, request): queryset = User.objects.all() serializer = AccountSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, email=None): queryset = User.objects.all() user = get_object_or_404(queryset, email=email) serializer = AccountSerializer(user) return Response(serializer.data) I have two email addresses in the database. My API client is httpie. When I send a GET request to http://127.0.0.1:8000/api/accounts/ I get back those two emails. So this part works fine. However, when I provide an email address that doesn't exits in the database (as Params or Headers), I again get those two emails instead of 404. I did a little bit of research and change the code like this: class AccountViewSet(viewsets.ViewSet): def list(self, request): queryset = User.objects.all() serializer = AccountSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, email=None): queryset = User.objects.all() try: user = get_object_or_404(queryset, email=email) except User.DoesNotExist: return Response(status=404) serializer = AccountSerializer(user) return Response(serializer.data) Again, 200 with those two emails. Even when I provide an email that does exists, I get both in response. I can't figure out what I'm missing. -
How to maintain data integrity in django
How can I maintain data integrity in django? I see that there is optimistic locking, or mvcc, but I don't know how to implement it. Also, are these the same thing? I think I can implement pessimistic locking using select_for_update. I heard that F() gets the latest information on the database side and adds values to it to maintain consistency, but is it ok for simultaneous cases? I asked chatgpt and chatgpt said that mvcc and optimistic locking are implemented by default by the database, is this true? -
I want to select a record from table to go another page in django
i have a table in my template have a many records that retrieved from the database, each row have a select option that when a user selects an option and click on the button, it must be take him to another page. my template.html: <table id="tblToExcl" class="table table-striped table-bordered table-sm"> <thead class="thead-dark"> <tr> <th>رقم الكتاب</th> <th>تاريخ</th> <th>تاريخ الاضافة</th> <th>ملاحظات</th> <th>اﻻجراء</th> </tr> </thead> <tbody> {% for doc in docs %} <tr> <td>{{ doc.number }}</td> <td>{{ doc.date|date:"Y-m-d"}}</td> <td>{{doc.created_at|date:"Y-m-d"}}</td> <td>{{ doc.note }}</td> <td>{{ doc.status }}</td> <td> <a href="/edit/{{ doc.id }}"><span class="glyphicon glyphicon-pencil" ><i class="far fa-edit" style="color: #116014;"></i></i></span></a> <a href="/delete/{{ doc.id }}"><i class="far fa-trash-alt" style="color: #bf5a40;"></i></a> <a href="/download/{{ doc.id }}"><i class="far fa-file-pdf" style="color: #204a87;"></i></a> </td> <td> <select id="choices" style="background-color:DodgerBlue; color: white;"> <option value="/deliver/{{ doc.id }}/{{doc.number}}/{{doc.date}}/{{doc.note}}/{{doc.document}}/{{doc.status}}">الموارد البشرية</option> <option value="">المالية</option> </select> <button type="button" id="go-button" class="button"><span>تحويل</span></button> </td> </tr> {% endfor %} </tbody> </table> urls.py: urlpatterns = [ path("", views.index, name="index"), path("show", views.show, name="show"), path("docs", views.documents, name="docs"), path("maward-show", views.show_maward, name="maward-show"), path("deliver/<int:id>/<int:number>/<str:date>/<str:note>/<path:document>/<str:status>", views.deliver, name="deliver"),] **views.py: ** def deliver(request, id, number, date, note, document, status): print(document) var = Maward.objects.create(id=id, number=number, date=date, note=note, document=document, status=status) time.sleep(3) return redirect("/show") i added a javascript code to my template as following: <script> $(document).ready(function() { $('#go-button').click(function() { // Get the selected choice var selectedChoice = … -
Django migrations not working properly in ecs
I have a django application on ecs. I push the code to github along with the migrations files. I have a script that runs the migrate command when I deploy. I can create a superuser but when I try to login to admin panel I get relation user_user does not exist error, but when I connect to the RDS directly form my local system I can login, but not from the domain which is attached to the elb -
Unable to run the django server
i'm trying to laucn the django with the command python manage.py runserver but i got this error: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is Fa is False. here is my settings project: DEBUG = True ALLOWED_HOSTS = [] i've tried all the solution proposed by others on the relative question with mine but the difference is that i've not change the settings variable Debug so their solution don't work for me. like to change the value of list settings variable ALLOWEG_HOSTS but it's not working for me. -
Django-Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
There some questions related to this but no answers are helped. I often come accross errors like that but cannot figure out what causes problems. My projects has been running fine but suddenly all of them which using postgresql are stopped, giving following error. Traceback (most recent call last): File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/var/www/crm/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) File "/var/www/crm/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 275, in get_new_connection connection = self.Database.connect(**conn_params) File "/var/www/crm/venv/lib/python3.8/site-packages/psycopg/connection.py", line 728, in connect raise ex.with_traceback(None) psycopg.OperationalError: connection is bad: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/var/www/crm/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/var/www/crm/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.8/contextlib.py", line 74, in inner with self._recreate_cm(): File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/transaction.py", line 198, in __enter__ if not connection.get_autocommit(): File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 464, in get_autocommit self.ensure_connection() File "/var/www/crm/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/utils.py", … -
pathlib.py" is overriding the stdlib module "pathlib"
Creating a Django app in a condo virtual environment(djenv) created the html, updated views.py and urls.py when updating settings.py, getting a problem for this line of code from pathlib import Path "C:\test1\djenv\Lib\pathlib.py" is overriding the stdlib module "pathlib" when I renamed pathlib.py, Django doesn't work properly Is there a way override the stdlib pathlib and use the virtual environments pathlib.py or are there any other fixes for this problem -
Django join tables with two or more FK conditions
I want to join models B and C with two conditions, data_a and human in model_B, and data_a and autor in model_C, but how do I do it with Django ORM class user(models.Model): data_1 = models.CharField(max_length=60) data_2 = models.SmallIntegerField() data_3 = models.IntegerField(blank=True, null=True) class model_A(models.Model): data_1 = models.CharField(max_length=60) data_2 = models.SmallIntegerField() data_3 = models.IntegerField(blank=True, null=True) class model_B(models.Model): data_a = models.ForeignKey(model_A) human = models.ForeignKey(user) data_2 = models.IntegerField() class model_C(models.Model): data_a = models.ForeignKey(model_A) author = models.ForeignKey(user) data_1 = models.CharField(max_length=5) data_2 = models.IntegerField() additional conditions on join in django I've seen this place, but I don't know if it's applicable to my situation -
Django bulk_create() with inexistent ForeignKey
I have 2 models. For simplicity, I deleted all unnecessary fields. class User(models.Model): id = models.CharField(max_length=36, primary_key=True, null=False) age = models.IntegerFiels(default=-1) and class Device(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) Through the API, I receive information about devices and create a list with devices. devices = [] for device_data in data: devices.append( Device( user_id=device_data("user_id") ) ) Once I have the list of devices, I add it to the database. Device.objects.bulk_create(devices, ignore_conflicts=True) The problem is that if, when creating a Device, I specified a user_id that is not in the database, I will get a crash because I am trying to link with a non-existent id. Now to get around this I do the following: devices = [] users = [] for device_data in data: users.append( User( id=device_data("user_id", age = -1) ) ) devices.append( Device( user_id=device_data("user_id") ) ) Then, when saving: User.objects.bulk_create(users, ignore_conflicts=True) Device.objects.bulk_create(devices, ignore_conflicts=True) User.objects.filter(age=-1).delete() How can I make sure that when saving, if the specified user_id does not exist, this device is not added? Or add a device, while creating a User with this user_id, but with the rest of the fields by default, and then, at the end, I will delete all users, and with them all devices, where age … -
Django queryset not filtering correctly based on end_date and current_time
I'm encountering an issue with my Django project where I have a model Service with an end_date field. I want to filter services based on whether their end_date is in the future, but I'm facing unexpected behavior. model.py: from django.db import models from apps.user.models import CustomUser from apps.location.models import City from django.utils import timezone class Area(models.Model): name = models.CharField(max_length=70,unique=True) def __str__(self): return self.name class Type_of_housing(models.Model): name = models.CharField(max_length=100,unique=True) areas = models.ManyToManyField(Area,blank=True) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class Subcategory(models.Model): name = models.CharField(max_length=100,unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name class Service(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) type_of_housing = models.ForeignKey(Type_of_housing, on_delete=models.CASCADE) area = models.ForeignKey(Area, on_delete=models.CASCADE) title = models.CharField(max_length=50) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) location_address = models.CharField(max_length=100) city = models.ForeignKey(City,on_delete=models.CASCADE) is_visible = models.BooleanField(default=True) end_date = models.DateTimeField() def __str__(self): return self.title def save(self, *args, **kwargs): if not self.end_date: # Calculate the end date as 14 days from the current date and time self.end_date = timezone.now() + timezone.timedelta(days=14) super().save(*args, **kwargs) class ServiceImage(models.Model): service = models.ForeignKey(Service, on_delete=models.CASCADE) image = models.ImageField(upload_to='service_images/') def __str__(self): return f"Image for Service: {self.service.description}" and view.py: def service_list(request): current_time = timezone.now() print("Current Time:", current_time) services = Service.objects.all() for service …