Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django i18n cannot use translated text in a dict
I am unable to store the translated texts in a dict class TestAPIView(APIView): def get(self, request): return Response({'msg': _("My error msg")}) The code above works. However when I tried to put the text into a dict. msg = { 123 : _("My error msg") } class TestAPIView(APIView): def get(self, request): return Response({'msg': msg[123]}) This doesn't translated the text. I have tried rerunning the makemessages and compilemessages, but it doesn't help. Any help? -
im trying to test this but it dont work pls help in django python
i dont know how to test this, pls can you guys find a way to test this i dont get it and i dont find videos on youtube aswell.I'm pretty new to this and so stressed because im so bad at programming right now. @login_required def update_billing_information(request: HttpRequest) -> HttpResponse: user = User.objects.get(pk=request.user.pk) form = BillingForm(instance=user) if request.method == "POST": form = BillingForm(instance=user, data=request.POST) if form.is_valid(): user = form.save() return redirect('show_billing_information') ctx = {"form": form} return render(request, "customer/_billing_edit.html", ctx) @login_required def show_billing_information(request: HttpRequest) -> HttpResponse: user = User.objects.get(pk=request.user.pk) ctx = {"user": user} return render(request, "customer/_billing_show.html", ctx) and chatgpt gave me this shit User = get_user_model() class BillingInformationTestCase(test.TestCase): def setUp(self): self.user = User.objects.create_user(email='Testuser32@gmail.com', password='testpassword', dob = date(1990, 1, 1)) self.factory = test.RequestFactory() self.client = Client() self.client.force_login(self.user) def test_update_billing_information_valid_form(self): request = self.factory.post('/update_billing_information/') request.user = self.user form_data = { 'billing_info': 'Updated Billing Info', "first_name" : 'Tim', "last_name" : 'Herb', "address1" : '123 Main Street', "address2" : 'Apt 2B', "city" : 'New York', "state" : 'Ny', "zip" : '12345', } request.POST = form_data response = update_billing_information(request) self.assertIsInstance(response, HttpResponseRedirect) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/views/customer/billing') def test_update_billing_information_invalid_form(self): request = self.factory.post('/update_billing_information/') request.user = self.user form_data = { 'billing_info': 'Updated Billing Info', "first_name" : '', "last_name" : '', "address1" … -
mod_wsgi with two python versions
I have an Ubuntu-18.04 LTS EC2 serving a django application with mysql Ver 8.0.16, Apache/2.4.29 and mod_wsgi/4.6.5complied withpython3.6. Now, I am targeting to deploy a new django application in the same Ubuntu EC2 serve and it requires python3.11+ virtualenv for installing its requirements.txt, now i am facing issues while deploying the new application. here are few other informations, Using Pyenv for creating virtualenvs, mod_wsgi is installed from source and compiled using ./configure --with-python=/home/ubuntu/.pyenv/shims/python3.6 after deploying the new django application the domain returns 500 error and logs are as follows api.log [03/Aug/2023:18:42:14 +0000] "GET / HTTP/1.1" 500 816 [03/Aug/2023:18:43:17 +0000] "GET / HTTP/1.1" 500 816 [03/Aug/2023:18:43:17 +0000] "GET / HTTP/1.1" 500 816 [03/Aug/2023:18:43:17 +0000] "GET / HTTP/1.1" 500 816 [03/Aug/2023:18:43:18 +0000] "GET / HTTP/1.1" 500 816 [03/Aug/2023:18:43:18 +0000] "GET / HTTP/1.1" 500 816 api_error.log [Thu Aug 03 18:43:18.047679 2023] [wsgi:error] [pid 170353:tid 140404074731072] mod_wsgi (pid=170353): Failed to exec Python script file '/var/www/project/newdjango/wsgi.py'. [Thu Aug 03 18:43:18.047724 2023] [wsgi:error] [pid 170353:tid 140404074731072] mod_wsgi (pid=170353): Exception occurred processing WSGI script '/var/www/project/newdjango/wsgi.py'. [Thu Aug 03 18:43:18.047795 2023] [wsgi:error] [pid 170353:tid 140404074731072] Traceback (most recent call last): [Thu Aug 03 18:43:18.047810 2023] [wsgi:error] [pid 170353:tid 140404074731072] File "/var/www/project/newdjango/wsgi.py", line 12, in <module> [Thu Aug 03 … -
Pycharm is not allowing me to make a password for a super user on my Django project
I am trying to create a superuser on the terminal on pycharm but It's not typing anyting when I try to create a password for that superuser in the terminal. I tried to recall the command "python manage.py createsuperuser" a few times but I still ran into the same issue. I was expecting it to type in the password, but no matter what I type it's not typing anything. I am following this tutorial: Python Tutorial-Python Full Course For Beginners and my issue is at 5 hrs and 38 mins. I am able to type in the username and email, but just not the password. -
Overlay search results from one div onto the one below
I created a search bar that shows results as a list. Initially, the results of the search bar would push the rows below it down to create space. I want it to overlay on top of the divs below it, but it cuts off and will not show the full list of results. I have tried changing z-index and using overlay: auto and position: absolute to no avail. Here are images of what I mean: Here is the code to set up the divs and rows in the form. Note: every field is its own search bar. <form id="part-data-form" name="part-data-form" method="post" class="d-flex flex-column" style="min-width: 0; min-height: 0"> {% csrf_token %} <div class="d-flex flex-grow-1 flex-column p-3 border border-secondary rounded m-2" style="overflow: auto; min-width: 0; min-height: 0"> <div class="row"> {% for field in form %} <div class="col-4 form-group"> <label class="fw-bold" for="{{ field.auto_id }}" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{{ field.field.tooltip|default:field.label }}"> {{ field.label }} {% if field.field.required %}<span class="text-danger">*</span>{% endif %} </label> {% if field.label == 'NHA Override' %} {{ field }} <div id="results"></div> {% else %} {{ field }} {% endif %} {% endif %} -
Django - best way to set up models for timeclock app?
I am working on an employee timeclock app in Django mostly as a test project. I am a newbie and I am not sure how best to set up the models, etc. I could create clockin and clockout models and reference the user as a foreign key. However then I am not sure the best way to calculate time between multiple clock-in and clock-out events in one day. Any ideas about the best way to handle this most efficiently? Thank you for any suggestions. -
How to reference newrelic keys via settings.py
I am just using NewRelic for the first time. I have the new relic.ini file, which includes the license_key and app_name hard coded, in my Django Python repository and have updated my manage.py script to be as so: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import newrelic.agent newrelic.agent.initialize('newrelic.ini') import os import sys def main(): ..... if __name__ == '__main__': main() When I run my api locally via ./manage.py runserver I can see the logs being tracked in NewRelic which is good. However, I'm wanting to remove the hardcoded license_key and app_name from the newrelic.ini file so that I can reference environment variables. I have read this documentation https://docs.newrelic.com/docs/apm/agents/python-agent/configuration/python-agent-configuration/#server-side-configuration which outlines the environment and config variables. I added this to my settings.py file so that I can override the env variables on deployment: NEW_RELIC_APP_NAME = "My API" NEW_RELIC_LICENSE_KEY="XXXXXXXXXXXXXXXX" I have tried removing license_key and app_name entirely from newrelic.ini keeping the variables but setting them equal to "" keeping the variables but setting license_key = NEW_RELIC_LICENSE_KEY but I can't seem to get it tracking without it being hardcoded in the newrelic.ini file So my question - how can I use environment variables with the newrelic.ini file? thanks in advance -
Using Python to Pull Data from XLSX file stored online
I'm building an app using Django that needs to be able to pull data from sheets stored in an XLSX file. For testing I've used files stored locally, but now that I need to put it online I need to be able to work with files stored online. I've tried working with files stored on SharePoint but haven't been able to work with the raw file. Is there a place these files could be stored where I can access them with Python or a way to make them accessible if stored somewhere like SharePoint? I also have to work with CSV files stored online but was able to do so by adding them to GitHub and accessing the raw file as shown in the image below. Is this possible anywhere for non CSV excel files? -
Django - limit_choices_to users within a group model
I have a group models with members and one admin which looks like this: class Group(models.Model): name = models.CharField(unique=True, max_length=255) members = models.ManyToManyField(User, related_name='members') is_admin = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, limit_choices_to={'members': True}) I want to show only members which are part of the group to the is_admin field. I tried the limit_choices_to method and referred the members but it is not working when I try to display the users in a form like this: form = EditGroupForm(instance=group). How can I do so? -
DJANGO: Error ninja.errors.ConfigError: Router@'/xxxxxxxx/' has already been attached to API NinjaAPI:1.0.0
I am running a Django application in Docker when I spinup the docker container I get the error Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/utils/deprecation.py", line 94, in __call__ response = response or self.get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 128, in handle_uncaught_exception callback, param_dict = resolver.resolve_error_handler(500) File "/usr/local/lib/python3.9/site-packages/django/urls/resolvers.py", line 597, in resolve_error_handler callback = getattr(self.urlconf_module, 'handler%s' % view_type, None) File "/usr/local/lib/python3.9/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.9/site-packages/django/urls/resolvers.py", line 577, in urlconf_module return import_module(self.urlconf_name) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/repo/repo/repo/urls.py", line 28, in <module> api.add_router("/xxxxx/", xxxxx_router) File "/usr/local/lib/python3.9/site-packages/ninja/main.py", line 367, in add_router self._routers.extend(router.build_routers(prefix)) File "/usr/local/lib/python3.9/site-packages/ninja/router.py", line 366, in build_routers raise ConfigError( ninja.errors.ConfigError: Router@'/xxxxx/' has already been attached to API NinjaAPI:1.0.0 The start script start.sh using gunicorn echo Starting Gunicorn. export … -
Traefik2 as reverse_proxy for Nginx in django production docker-compose
I have managed to build a small Django app some basic things. Localy works all fine and I'd like to start this WebApp on a production server I already have running. On this server are already some docker-compose configurations running were a traefik2 works as a revers_proxy with letsencrypt certifikates. So far so good. As I designed my django project with nginx as static file delivery I'd like to use it and let traefik2 work as revers_proxy in front of nginx. docer-compose.pro.yml version: "3.9" # docker-compose for production # It is important that the .env.prod is used. # For this, docker-compose must always be executed # with the command docker-compose -f docker-compose.pro.yml --env-file .env.prod. services: web: build: context: . dockerfile: ./compose/Dockerfile restart: always command: gunicorn project.wsgi:application --bind 0.0.0.0:8000 env_file: - ./.env.prod expose: - 8000 volumes: - static_volume:/code/staticfiles - media_volume:/code/mediafiles depends_on: - redis - db networks: - pjnet db: image: postgres:15 restart: always volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=${DB_USERNAME} - POSTGRES_PASSWORD=${DB_PASSWORD} - POSTGRES_DB=${DB_NAME} networks: - pjnet redis: image: redis:7 networks: - pjnet celery: build: context: . dockerfile: ./compose/Dockerfile restart: always command: celery -A project worker -l info volumes: - .:/code env_file: - ./.env.prod depends_on: - db - redis - web networks: … -
Django can not send mail but smtplib can
I was trying to use django's accounts system and configured some templates. When i tried to do password reset it said "SMTPRecipientsRefused at /accounts/password_reset/". But it works when i send an email with smtplib. In django settings: # EMAIL EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "mail.X.com" EMAIL_PORT = 587 EMAIL_HOST_USER = "X@mydomain" EMAIL_PASSWORD = "password" And the error: Exception Type: SMTPRecipientsRefused at /accounts/password_reset/ Exception Value: {'X@gmail.com': (450, b'4.7.1 We do not relay gmail.com')} But i knew i used the same mail before with smtplib and tried again, and it worked. >>> import smtplib >>> from email.message import EmailMessage >>> mail_server = "mail.X.com" >>> mail_username = "X@mydomain" >>> mail_password = "password" >>> mail_port = 587 >>> msg = EmailMessage() >>> msg["Subject"] = "subject test" >>> msg["From"] = mail_username >>> msg["To"] = "X@gmail.com" >>> server = smtplib.SMTP(mail_server, mail_port) >>> server.login(mail_username, mail_password) (235, b'2.7.0 Ok') >>> server.send_message(msg) {} >>> server.quit() (221, b'2.0.0 Bye') I tried adding DEFAULT_FROM_EMAIL = "X@mydomain" to the settings.py but it didn't make any difference. I tried adding EMAIL_USE_TLS=True but it said: SSLCertVerificationError at /accounts/password_reset/ [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Hostname mismatch, certificate is not valid for 'mail.X.com'. (_ssl.c:1131) -
How to run both react and django on https
I had a react+django app. The react app was on http://my.domain.com, and it called the django app that is on http://my.domain.com:8000. Now, I have installed an SSL certificate and changed the react app to run on https://my.domain.com. However, whenever it tries to call the django app on http://my.domain.com:8000, I get an error Blocked loading mixed active content “http://my.domain.com:8000/auth/”. This makes sense, because I really have mixed content: an https page (the react app) tries to call http (the django app). On the other hand, if I change the API call to “https://my.domain.com:8000/auth/”, it does not work at all (it hangs). How can I let django accept calls through SSL, so that I do not get these mixed content errors? -
KeyError: 'room_name' in Django channels
I'm stuck on this KeyError issue. Can anyone advise what's the problem? First I'll show you my code here. class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room await(self.channel_layer.group_add)(self.room_group_name, self.channel_name) await self.accept() routing.py websocket_urlpatterns = [ re_path(r'^ws/(?P<room_name>\w+)/$', ChatConsumer.as_asgi()), ] urls.py path('chat/<str:room_name>/', views.ChatAPIView.as_view()) and The Error is - KeyError: 'room_name'. I referred to the Django docs, but the difference is I used ApiView in views.py. I'm using this project for an android project as a server. Need to be fixed the KeyError. -
Django relative_name issues on model Inheritance
I have an issus with inheritance on models and reverse relations. Here my models : class A(B): designation = CharField() class B (): owner = ForeignKey(A, null=True, blank=True, related_name='sites') name = CharField() street1 = CharField() class C(): name = CharField() relation_a = ForeignKey(A, related_name='all_elements', null=True, blank=True) relation_b = ForeignKey(B, related_name='elements', null=True, blank=True) Firstly my model A inherits from the model B for get all address informations.Model A can have several sites(B) I have an other model C with foreign key to model A and another to model B. For each element B I want get all elements. This work fine: for b in B.objects.all(): print(b.elements.all()) For get all elements link to A is work: print(A.all_elements.all()) But I can't get just the element C linked to A by the relation_b print(A.elements.all()) I got an empty list. If I want only this element I need to pass by B models B.objects.get(id=A.id).elements.all() This is the first issues. Secondly, my main problem is with serializer. My serializer : A_Serializer(B_Serializer): class Meta: model = A fields = [ 'designation', 'street1', 'site', 'all_elements', 'elements', ] expandable_fields = { 'sites': (B_Serializer, {'many'=True} 'all_elements': (C_Serializer,{'many':True}), 'elements': (C_Serializer,{'many':True}), } In DRF I can expend the all_elements in serializer A. … -
csv download is not including all the results in a django application
im trying to build a web app with python and django, in this application a user can enter a list of websites, the results will show the website status, the website title, the website summary, the email, the phone number, facebook and instagram links if present. At the end the user can download the results as csv, btw the csv is showing only 1 result, and even incomplete (the website, the phone, the email, fb and instagram are missing). What am i doing wrong? here is the main file # website_checker/checker/views.py from django.shortcuts import render from django.http import HttpResponseRedirect from django.shortcuts import render, HttpResponse from django.urls import reverse import requests from bs4 import BeautifulSoup from .utils import get_business_summary, extract_emails, extract_phones, extract_social_media_links import spacy import re import csv import io # Function to get a business summary from the text def get_business_summary(text): nlp = spacy.load('en_core_web_sm') doc = nlp(text) sentences = [sent.text.strip() for sent in doc.sents] business_summary = '' for sent in sentences: # You can add more conditions to extract business-specific information from the text if 'business' in sent.lower() or 'company' in sent.lower(): business_summary = sent break return business_summary # Function to extract emails from the text def extract_emails(text): # Use … -
Error when trying to delete model instance in Django 4.2.2
I've been trying to delete an existent instance from the user table (mysql) but I keep getting error from the user.delete() this is the my viewpoint: @api_view(['GET', 'PUT', 'DELETE']) def user_api_id(request): try: id = request.GET.get('id') user = User.objects.get(pk=id) if request.method == 'GET': serializer = UserSerializer(user) return Response(serializer.data) elif request.method == 'PUT': serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': try: user.delete() return Response(status=status.HTTP_204_NO_CONTENT) except ValidationError as ve: return Response({"error": str(ve)}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) When I launch a DELETE request I get this: "error": "(1292, \"Truncated incorrect DOUBLE value: 'john'\")" (btw the user I want to delete has id='john') This is my User model: class User(models.Model): id = models.CharField(primary_key=True, max_length=50) password = models.CharField(max_length=50) name = models.CharField(max_length=25) lastname = models.CharField(max_length=25) age = models.IntegerField() gender = models.CharField(max_length=6) email = models.CharField(max_length=50, blank=True, null=True) phone = models.CharField(max_length=50, blank=True, null=True) address = models.CharField(max_length=50, blank=True, null=True) educationallevel = models.CharField(db_column='educationalLevel', max_length=50, blank=True, null=True) # Field name made lowercase. experience = models.CharField(max_length=20, blank=True, null=True) is_active = models.BooleanField(default=True) is_anonymous = models.BooleanField(default=False) is_authenticated = models.BooleanField(default=True) USERNAME_FIELD = 'id' REQUIRED_FIELDS = [] class Meta: managed = False db_table = 'user' And this is the … -
DRF Spectacular - @extend_schema subclass method for Serializers
Im using DRF_SPECTACTULAR to generate swagger DOC from my DRF Project. I have a GenericViewSet that implement CRUD methods. Over each ones, I have extend_schema decorator. Take this one as example: @extend_schema( # extra parameters added to the schema parameters=[ OpenApiParameter(name = "jwt_token", description="JSON Web Token", required=True, type=str), OpenApiParameter(name = "id", type = OpenApiTypes.STR, location=OpenApiParameter.PATH , description = "ID "), ], methods=["GET"], description = 'Return a serialized User', request = JWTRequestSerializer, responses = { 200: GenericResponseSerializer }, ) def retrieve(self, request, pk=None): I Have a lot of ViewSet for every Models that extends the Generic and override some methods to make it specific for the model. I need something like this for the Serializer in extend_schema. In the example, I have GenericResponseSerializer but I need every subclasses that extends this SuperClass, return its own specific Serializer. I've tried with a static method: @staticmethod def getRetrieveSerializer(): return GenericResponseSerializer() ... responses = { 200: getRetrieveSerializer }, ... It works well but it always return the SuperClasses method even if Im extending it. Unfortunally in decorator, I cant access self so I cant use a method that is overwritten at runtime. Is there a way to reach this goal? Maby with reflection? -
Django is not sending POST request
I am building a simple web app with Django and got into this weird situation. I want to delete an entry of a model but the html won't send any post request. delete.html {% extends 'main.html' %} {% block content %} <form method="POST" action=""> {% csrf_token %} <p> Are you sure to delete "{{obj}}" ?</p> <a href="{{request.META.HTTP_REFERER}}">GO BACK </a> <input type="submit" value="Confirm"> </form> {% endblock %} View for delete.html in views.py def delete_room(request, pk): room = Room.objects.get(id=pk) if request.method == 'POST': room.delete() return redirect('home') return render(request, 'base/delete.html', {'obj':room}) Model in models.py class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) # participants = created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: ordering = ['-updated', '-created'] urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('room/<str:pk>', views.room, name='room'), path('create-room/', views.create_room, name='create-room'), path('update-room/<str:pk>', views.update_room, name='update-room'), path('delete-room/<str:pk>', views.delete_room, name='delete-room'), path('about/', views.about, name='about'), ] I've tried sending POST request from other templates and it woorks fine like adding new rooms and updating existing ones. When I click on Confirm, it shows nothing in terminal. -
Issue with swagger docs in django views
I have a view in my django project like this class SampleView(MixinPermissionsByAction, MixinSerializerByAction, generics.ListCreateAPIView): serializer_class = SampleCreateSerializer permission_classes = (IsAuthenticated) permissions_by_action = {"POST": (SomePermission,)} serializer_by_action = {"GET": SampleListSerializer} filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_fields = ["status"] ordering_fields = ["-updated", "-created"] search_fields = [ "name", ] queryset = None throttle_classes = [SomeThrottling] def get_queryset(self): <get request logic here....> in my serializers.py class i have two serializers. one for get rquest and other for post request class SampleListSerializer(serializers.ModelSerializer): <some fields here> class Meta: model = MyModelName exclude = <fields to be excluded> class SampleCreateSerializer(serializers.ModelSerializer): <some fields here> class Meta: model = MyModelName fields = "__all__" def create(self, validated_data): <logic for post request> I want to add get and post methods in swagger docs and tried following added @method_decorator above SampleView but it did not worked added @swagger_auto_schema above get_queryset method in view class and create method in SampleCreateSerializer here is my swagger implementation schema_view = get_schema_view( openapi.Info( title="My API", default_version="v1", description="API documentation for MyAI", ), public=True, permission_classes=(permissions.IsAdminUser, ), authentication_classes=(SessionAuthentication, ), ) and in urlpatterns path('docs/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui') Need help here to implement swagger on my above views. I have tried different stuff that i mentioned above but it did not work. … -
Setting minimum-width in line [Django]
Consider class MyTable(tables.Table): name = tables.Column(attrs={'cell': {'min-width': '200px'}}) Is this the right syntax for setting the minimum width of the 'name' column to 200px? This doesn't work on my machine. The 'name' column doesn't respond to variations in the min-width. -
Why are `connection.wait psycopg` suddenly high?
I noticed that my django tests became slow so I profiled them using pyinstrument. I noticed that connection.wait psycopg/connection.py:949 were taking a lot more time than before. So I focused on profiling this chunk of code that just does 2 queries: def test_foo(self): from pyinstrument import Profiler profiler = Profiler() profiler.start() foos = Foo.objects.filter(status=True) nb_foos = foos .count() first_foo = foos.first() profiler.stop() profiler.print() And the results are: BEFORE: 0.005 foo.py:93 ├─ 0.004 BaseFooQuerySet.first django/db/models/query.py:1050 │ [27 frames hidden] django, inspect, psycopg │ 0.001 Connection.wait psycopg/connection.py:949 └─ 0.001 BaseFooQuerySet.count django/db/models/query.py:597 [6 frames hidden] django AFTER: 0.543 foo.py:62 ├─ 0.275 BaseFooQuerySet.count django/db/models/query.py:597 │ [9 frames hidden] django, psycopg │ 0.274 Connection.wait psycopg/connection.py:949 └─ 0.268 BaseFooQuerySet.first django/db/models/query.py:1050 [10 frames hidden] django, psycopg 0.266 Connection.wait psycopg/connection.py:949 It's 100x slower. It's running on the same python env (python version and requirements). Python 3.11.3 Django==4.2.4 psycopg==3.1.9 psycopg-c==3.1.9 psycopg-pool==3.1.7 The "before" version is using an old commit so obviously something changed in my code then but what could this be to have such an impact on the db connection? -
Django custom filter - to convert datetime
I am working on a Django app and need to show datetime on the UI. the datetime is UTC format and I need to convert it into local timezone of the user. for this I implemented this custom filter in my app from django import template import pytz register = template.Library() @register.filter def convert_to_localtime(value, user_tz): if not value: return value local_tz = pytz.timezone(user_tz) local_time = value.astimezone(local_tz) print("Conversion function",value, local_time) return local_time In the template I am using this custom filter like this {%load custom_filters%} <span class="text-center match-date-time">{{ match.start_time|convert_to_localtime:user_tz}}</span> I can see that the custom filter is executing and converting datetime properly into local timezone as I can see following output for the print statement Conversion function 2023-08-03 17:30:00+00:00 2023-08-03 23:00:00+05:30 But on the UI I still the UTC datetime rather than the converted time. What am I missing? -
Django Edited images not showing up after processing in views
The website allows user to upload an image and will be edited and shown to the user. (learning to use Pillow for image editing). It gives no error in the terminal, the images are getting saved, but not showing up after edit. Is there issue with how the image is generating? Or in the javascript? Terminal also looks fine, showing this: [03/Aug/2023 15:28:32] "GET / HTTP/1.1" 200 1445 [03/Aug/2023 15:28:37] "POST / HTTP/1.1" 200 1521 index.html: <!DOCTYPE html> <html> <head> <title>Image Editor</title> <style> img { max-width: 400px; max-height: 400px; } </style> </head> <body> <h1>Image Editor</h1> <form action="{% url 'edit_image' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="image_file" id="image_file" onchange="previewImage(event)"> <input type="submit" value="Upload and Edit"> </form> <div id="imagePreview"> <h2>Uploaded Image Preview:</h2> <img id="preview" src="" alt="Uploaded Image"> </div> {% if edited_image %} <h2>Edited Image:</h2> <img src="{{ edited_image.url }}" alt="Edited Image"> {% endif %} <script> function previewImage(event) { const fileInput = event.target; const imagePreview = document.getElementById("imagePreview"); const preview = document.getElementById("preview"); if (fileInput.files && fileInput.files[0]) { const reader = new FileReader(); reader.onload = function (e) { preview.src = e.target.result; }; reader.readAsDataURL(fileInput.files[0]); imagePreview.style.display = "block"; } else { preview.src = ""; imagePreview.style.display = "none"; } } </script> </body> </html> views.py: from django.shortcuts import render … -
Time Limit not Working for Django Celery 5.3.1
I am having a trouble with trying time_limit and soft_time_limit feature in celery and django app. import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings') app = Celery('server') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.update( task_soft_time_limit=1, task_time_limit=1, ) # Load task modules from all registered Django apps. app.autodiscover_tasks() @app.task(bind=True, ignore_result=True) def debug_task(self): print(f'Request: {self.request!r}') I have this celery configuration. I'm trying time limit config with for celery task in django and run this task. from celery import shared_task from celery.exceptions import SoftTimeLimitExceeded from celery.signals import task_success, task_failure, task_prerun import time from server.celery import app shared_task def scrape(domain: str, route: str = None): try: time.sleep(5) except SoftTimeLimitExceeded: print("Time Limit") @task_prerun.connect(sender=scrape) def scrape_prerun_notifier(task_id=None, task=None, *args, **kwargs): print("From task_prerun_notifier ==> Running just before add() executes") @task_success.connect(sender=scrape) def scrape_success_notifier(sender=None, result=None, **kwargs): print("Success") task_id = sender.request.id @task_failure.connect(sender=scrape) def scrape_failure_notifier(task_id=None, exception=None, *args, **kwargs): print("Failure") How ever, the scrape task always succeed without catching any exception. I've also tried modifying the decorator but it doesn't work either. @app.task(soft_time_limit=1, …