Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can anybody help me find a work remotely? [closed]
Hi hope you all doing well and you don't meet bugs indeed Im quite good at django i can say that im a full-stack with a solid python & JavaScript background. Please get in touch if you have any collaborative opportunities. Peace ✌️. Post. On LinkedIn and other platforms that offers remotes jobs ? -
Dynamic routing not working as expected in Nextjs
I am trying to create a dynamic route in nextjs but I am getting page not found error The page loads only when I give the url with the exact pathname of the page I have a Django Backend server set up I just call The RestApis Here is the error Error Screen here is the page when I pass the exact url enter image description here This is how I created the route in the app directory app/something/[id] And this is the screen I want to render page.tsx I am expecting to a dynamic url from where i can extract the id through params -
Need some advice on Phusion/Passenger setup
Okay, so.. I've never used this set of programs, so please be nice. I help a guy out with his hosted application on dreamhost. I mostly edit some HTML and python. However, it's pretty legacy and it's running phusion/passenger. It's a django site, but I don't think it's "deployed correctly" with django. Typically, I copy everything locally, make edits and run the application manually with something like: python manage.py runserver 0.0.0.0:8000 --verbosity 3 I then just copy over the changes.. However, some of the python modules are REALLY old. I wanted to try and update them. When I update django in my dev environment the application works fine. However, when I update django on the dreamhost environment the application bombs. (I do not have the exception handy) So, I want to more accurately reproduce this environment. I've built a docker container with apache, passenger, etc. I'd like to figure out how to put this application into the passanger environment so I can reproduce the environment. But I simple don't know how - and the amount of Googling i've done has not helped. -
Django: Set initial value of dropdown in form based on value in model
I am working on a ticketing web application using Django as a university. In there, assignees (tutors) need to be able to asign another tutor and change the status of the ticket ("Open", "In progress", ...). The current tutor and the current status is saved in the Ticket model: class Ticket(models.Model): creator = models.ForeignKey( Student, null=True, on_delete=models.SET_NULL ) assignee = models.ForeignKey( Tutor, on_delete=models.SET_NULL, blank=True, null=True ) current_status = models.CharField( max_length=2, choices=KorrekturstatusEnum.choices, default=KorrekturstatusEnum.OFFEN, ) description = models.TextField( default="Please provide as much detail as possibile." ) The life cycle of a ticket is saved in the Messages model: class Messages(models.Model): class ChangeTypeENUM(models.TextChoices): OPEN = "01", "Open" ASIGNMENT = "02", "Asignment" STATUS_CHANGE = "03", "Status change" MESSAGE = "04", "Message" class SenderENUM(models.TextChoices): TUTOR = "01", "Tutor" STUDENT = "02", "Student" student = models.ForeignKey( Student, on_delete=models.SET_NULL, null=True, related_name="student_messages", ) tutor = models.ForeignKey( Tutor, on_delete=models.SET_NULL, related_name="tutor_messages", null=True, blank=True, ) ticket = models.ForeignKey( ticket, on_delete=models.CASCADE, related_name="korrektur_messages" ) text = models.TextField(null=True, blank=True) created_at = models.DateTimeField(default=timezone.now) sender = models.CharField( max_length=2, choices=SenderENUM.choices, default=SenderENUM.STUDENT ) status = models.CharField( max_length=2, choices=KorrekturstatusEnum.choices, default=KorrekturstatusEnum.OFFEN, ) change_type = models.CharField( max_length=2, choices=ChangeTypeENUM.choices, default=ChangeTypeENUM.EROEFFNUNG, ) Changes to a ticket, including messages/comments are done by a from, I'm using a model form here. I am trying to … -
Add dynamic fields through django admin
I've looked around the stack but I cant find any answers. So I have a model like this: class DynamicModel(models.Model): config = models.JSONField() def __str__(self): return self.config what I want to do here now is to show the json field key-value pairs as standalone fields and also be able to edit them in the same way, like if they were each one a different field. This was the best way I could come up to create dynamic fields. So if I have a jsonfield like this: { "age": 23, "name": "John Doe", "gender": "Male" } I would have an `Age` field where I can edit the value or even remove the field alotgether. The changes would then reflect to the `JSONField`. My approach is like this: # forms.py from django import forms from .models import DynamicModel class DynamicModelForm(forms.ModelForm): class Meta: model = DynamicModel fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Check if 'config' is in the fields if 'config' in self.fields: # Extract JSON data from the instance or initialize an empty dictionary json_data = self.instance.config if self.instance and 'config' in self.instance else {} # Loop through the JSON data and add individual fields for key, value … -
AttributeError: type object 'Token' has no attribute 'objects'!, How to solve it?
I am trying to create a custom user blog API using class based views and token authentication. But both my register view and login view are not working properly. when I try to register user it throws an Attribute error and when I try to login it says "Method Not Allowed: /register/ [15/Feb/2024 22:36:47] "GET /register/ HTTP/1.1" 405 13614" I think I have made some mistakes on my views file but it seems like I am stuck and cant move ahead with this error. I also tried chatgpt but it was of no use, please help. this my github link for the repo https://github.com/Rohit10jr/cbv_blog_token_auth this is my register and login views class RegistrationAPIView(generics.CreateAPIView): queryset = CustomUser.objects.all() serializer_class = CustomUserSerializer permission_classes = [AllowAny] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = self.perform_create(serializer) token, created = Token.objects.get_or_create(user=user) headers = self.get_success_headers(serializer.data) return Response({'token': token.key, 'user': serializer.data}, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): return serializer.save() # return super().perform_create(serializer) # return super().perform_create(serializer) class LoginAPIView(generics.CreateAPIView): serializer_class = CustomUserSerializer permission_classes = [AllowAny] allowed_methods = ['POST'] # Allow both POST and GET requests def create(self, request, *args, **kwargs): email = request.data.get('email') password = request.data.get('password') user = authenticate(request, email=email, password=password) if user: login(request, user) serializer = self.get_serializer(user) … -
Why is my Filter not filtering the table?
In my views.py I am using class based views to show a table along with a filter and form(TO ADD new data). My previous pages have been working when I did not define any methods but for this page I need methods to work with . Please let me know why my filter is not working. Creating a new form also leads to a "'ChamberLogView' object has no attribute 'object_list'" error. If you have any idea on that please let me know. Thank You class ChamberLogView(SingleTableMixin, CreateView, FilterView): template_name = 'html/ChamberLog.html' model = ChamberLog table_class = ChamberLogTable form_class = ChamberLogForm filterset_class = ChamberLogFilter def get_table_data(self, *args, **kwargs): return ChamberLog.objects.filter(log_id = self.kwargs.get('pk')) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['ChamberLogInfo'] = ChamberLogInfo.objects.filter(pk = self.kwargs.get('pk')) return context def get_success_url(self): #print(self.pk) return HttpResponseRedirect(reverse('ChamberLog', kwargs={'pk': self.pk})) -
How do I get django to interact with html
So, I have the following question, I need to create a way for the object inserted within the field to be transferred to a within a single page but with different functions, and I managed to do this but in a way that In my opinion, it shouldn't be the best, that is, my goal is to optimize this if possible. Below is the code for the views, urls, forms, html. And detail, I don't intend to use Java, but if this is the only or best way, I'm willing to understand. #urls from django.urls import path from FrontEndProject import views urlpatterns = [ path('', views.RenderHomePage), path('test/', views.PostInfoHomePage, name='PostInfoHomePage') ] #views from django.shortcuts import render from .forms import * def RenderHomePage(request): return render(request, 'HomePageBody.html') def PostInfoHomePage(request): Info = '' if request.method == 'POST': form = FormInfo(request.POST) if form.is_valid(): Info = form.cleaned_data['PostInfo'] else: form = FormInfo() return render(request, 'HomePageBody.html', {'form': form, 'Info': Info}) #forms from django import forms class FormInfo(forms.Form): PostInfo = forms.CharField() #html <!DOCTYPE html> <html> <head> <title> Home page </title> </head> <body> <div> <form method="post" action="{% url 'PostInfoHomePage' %}"> {% csrf_token %} <input name="PostInfo" value="{{ form.PostInfo.value|default:'' }}"> <button>Take info</button> </form> <p>Information: {{ Info }} </p> </div> </body> </html> -
Saving django generated zip files
In a django project, I allow user to download multiple files as a zip file. But how do I limit the regeneration same zip content again and again? Is it bad practice to regenerate repeatedly? -
Problem when connecting Django and Flutter websockets
I'm trying to establish a connection with my Django backend and Flutter code using WebSockets, but unfortunately I'm unable to do so, went through many articles and videos and everyone is basically doing the same without receiving an error.. Please give a little push to, I'm kinda new into this. First of all I created a new django app called 'chat_app' (added it into settings.py), where I created a new model of my Messages: class Message(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) sender = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.content Then I made my consumers.py (here I'm a little bit confused, isn't it better to refer to my room unique_id instead of name, since the ID is unique and not the name in my case? Decided to stick with the tutorial.) class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group self.channel_layer.group_add( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group self.channel_layer.group_discard( self.room_group_name, self.channel_name ) Done the routing.py # The WebSocket URL pattern for chat rooms is defined by this code websocket_urlpatterns = [ re_path(r'ws/chat_app/(?P<room_name>\w+)/$', ChatConsumer.as_asgi()), ] Then added it into my project URLs: urlpatterns = [ path('admin/', … -
CSRF Token missing when it's there
I have a form, containing different form objects inside from the forms.py. However, when I try to submit the form, it says, "csrf verification failed" Here is the full template (sorry for the mess I'll structure the js later before launch) <!DOCTYPE html> {% load static %} {% load widget_tweaks %} <html lang="en"> <head> <head> <title>{{app.name}}</title> <!-- Meta Tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="author" content="Webestica.com"> <meta name="description" content="Bootstrap 5 based Social Media Network and Community Theme"> <!-- Dark mode --> <script> const storedTheme = localStorage.getItem('theme') const getPreferredTheme = () => { if (storedTheme) { return storedTheme } return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'light' } const setTheme = function (theme) { if (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches) { document.documentElement.setAttribute('data-bs-theme', 'dark') } else { document.documentElement.setAttribute('data-bs-theme', theme) } } setTheme(getPreferredTheme()) window.addEventListener('DOMContentLoaded', () => { var el = document.querySelector('.theme-icon-active'); if(el != 'undefined' && el != null) { const showActiveTheme = theme => { const activeThemeIcon = document.querySelector('.theme-icon-active use') const btnToActive = document.querySelector(`[data-bs-theme-value="${theme}"]`) const svgOfActiveBtn = btnToActive.querySelector('.mode-switch use').getAttribute('href') document.querySelectorAll('[data-bs-theme-value]').forEach(element => { element.classList.remove('active') }) btnToActive.classList.add('active') activeThemeIcon.setAttribute('href', svgOfActiveBtn) } window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { if (storedTheme !== 'light' || storedTheme !== 'dark') { setTheme(getPreferredTheme()) } }) showActiveTheme(getPreferredTheme()) document.querySelectorAll('[data-bs-theme-value]') .forEach(toggle => … -
Django not appening "/" on urls in a production server
I have a website written in Django. The website for production or development is deployed in a docker container. It is served over nginx that is also deployed in a docker container. On a development computer when the website is deployed and an address is input without a trailing "/" it is automatically appended and then redirected to the correct page. In a production server, this isn't happening. No redirection commences and the server returns 404. The only difference between development and production is that the production instance is run with SSL and a domain name. Here are my NGINX configs for both situations. Development: upstream django { server django_gunicorn:8000; } server { listen 80; location / { proxy_pass http://django; } location /static/ { alias /static/; } } Production: upstream django { server django_gunicorn:8000; } server { listen 443 ssl; ssl_certificate /ssl/live/fullchain.pem; ssl_certificate_key /ssl/live/privkey.pem; server_name website.mydomain.com; location / { proxy_pass http://django; } location /static/ { alias /static/; } } What is the issue, why production server is not redirecting? -
Django: static file serve does not work only when the url is "static/"
I have the following urls.py - urlpatterns = [ path('admin/', include("admin.urls")), path('accounts/', include("accounts.urls")), path('blogs/', include("blogs.urls")), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) In the settings.py I have - STATIC_URL = 'static/' STATIC_ROOT = 'static/' Here my static files in the static folder are showing a "Page Not Found (404)" error. But ifI change settings.STATIC_URL to anything else, it works. For example, if I do - static("anything/", document_root=settings.STATIC_ROOT), then it works, only the strings that start with 'static' does not work. Can anyone shed some light on this behaviour? -
JavaScript does not work when running Django on the local network. In 2024
My project ( https://github.com/Aleksandr-P/django-audio-recorder2024 ) works well on a local computer under Windows 10. If I run python manage.py runserver . After making changes: ..\web_project\settings.py ALLOWED_HOSTS = [] on the: ALLOWED_HOSTS = ['*'] And python manage.py runserver on python manage.py runserver 0.0.0.0:80 JavaScript stops working. How to fix it? I checked in the browser, the file audio_recorder\static\audio_recorder\recorder.js available. But it doesn't work. -
Python social auth and drf social oauth
I need help of community. In my Django project with django-rest-framework, we use JWT authentication and want to implement the social login by google. So, I installed and configured drf-social-oauth2 with backend google-oath2 in the project as shown in docs. settings.py INSTALLED_APPS = [ ... "social_django", "oauth2_provider", "drf_social_oauth2", ... ] ... TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ... ], }, } ] REST_FRAMEWORK = { ... 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', "oauth2_provider.contrib.rest_framework.OAuth2Authentication", "drf_social_oauth2.authentication.SocialAuthentication", ), } AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "drf_social_oauth2.backends.DjangoOAuth2", "social_core.backends.google.GoogleOAuth2", ) SOCIAL_AUTH_REQUIRE_POST = True ACTIVATE_JWT = True SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", ] SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = env( "SOCIAL_AUTH_GOOGLE_OAUTH2_KEY", default="SOCIAL_AUTH_GOOGLE_OAUTH2_KEY" ) SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = env( "SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET", default="SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET" ) urls.py urlpatterns = [ ... path("", include("social_django.urls", namespace="social")), path("auth/", include("drf_social_oauth2.urls", namespace="drf")), ] And now the question itself. How to implement redirection with the necessary data after user authorization on an external resource? I have a user's entry point with a redirect to google authorization path( "sign_in/google", views.AuthViewSet.as_view({"post": "sign_in_google"}), name="sign_in_google", ), method @extend_schema(request=None, responses={302: None}) def sign_in_google(self, request, *args, **kwargs): strategy = load_strategy(request) backend = load_backend( strategy=strategy, name="google-oauth2", redirect_uri=f"{self.request.scheme}://{self.request.get_host()}/complete/google-oauth2/", ) return do_auth(backend, REDIRECT_FIELD_NAME) And if I follow as per our requirements we need the user to redirect to google-oauth2 page and … -
Django App fails to deploy on AWS ElasticBeanstalk with pywin32==306
I am stuck here since 2 days. Someone please help. Django App works fine locally but fails to deploy on AWS ElasticBeanstalk with pywin32==306. Platform: Python 3.11 running on 64bit Amazon Linux 2023/4.0.8. I am using windows 11. Python Version : 3.12.2. PIP version : 23.3.2. Please find below requirements.txt: asgiref==3.7.2 awsebcli==3.20.10 beautifulsoup4==4.12.3 botocore==1.31.85 cement==2.8.2 certifi==2024.2.2 charset-normalizer==3.3.2 colorama==0.4.3 distlib==0.3.8 Django==4.2.10 django-bootstrap-v5==1.0.11 filelock==3.13.1 idna==3.6 jmespath==1.0.1 pathspec==0.10.1 platformdirs==4.2.0 psycopg-binary==3.1.17 psycopg2-binary==2.9.9 pypiwin32==223 python-dateutil==2.8.2 pywin32==306 PyYAML==6.0.1 requests==2.31.0 semantic-version==2.8.5 setuptools==69.0.3 six==1.16.0 soupsieve==2.5 sqlparse==0.4.4 termcolor==1.1.0 tzdata==2023.3 urllib3==1.26.18 virtualenv==20.25.0 wcwidth==0.1.9 whitenoise==6.6.0 Getting the following error: 2024/02/15 13:12:10.274129 [ERROR] An error occurred during execution of command [self-startup] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with requirements.txt file with error Command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt failed with error exit status 1. Stderr:ERROR: Could not find a version that satisfies the requirement pywin32==306 (from versions: none) ERROR: No matching distribution found for pywin32==306 Complete AWS Log : https://drive.google.com/file/d/1ZbS3aVnHS2fg8-e9QDihnhzuHxB_CPDf/view?usp=sharing I upgraded the PIP and also tried pywin32==306;platform_system == "Windows" but in vain. -
How works super().get_queryset() in Django?
I am trying to get a queryset of questions that have publication date before today's date, but I am getting an error in get_queryset raise ImproperlyConfigured(django.core.exceptions.ImproperlyConfigured: IndexView is missing a QuerySet. Define IndexView.model, IndexView.queryset, or override IndexView.get_queryset(). My code: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return super().get_queryset().filter(pub_date__lte=timezone.now()) But this code works: def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()) What I am doing wrong? Thanks in advance -
django-tailwindcss integration image not displayed
I already have a Django project with template file index.html but my image is not displaying I try everything including {% load static %} but still it is not working may be because i used {% load tailwind_tags %} and {% tailwind_css %} and i also created file as mentioned in Django official website for static file but still it is not working. -
can't run cron file with docker -compose what i can do?
I use Django and postgres to them, I wrote a script that scrapes data and writes to the database and another that dumps. And these scripts should run at a certain time, as if in the logs I see that it is raised, but when I run it, it does not work PS C:\Users\komar\django-scraper-6> docker exec -it scrap bash root@0296ba2fb7f3:~/django_scraper# supervisorctl status cron RUNNING pid 9, uptime 0:09:37 server EXITED Feb 15 10:26 AM root@0296ba2fb7f3:~/django_scraper# supervisorctl start server server: started root@0296ba2fb7f3:~/django_scraper# supervisorctl status cron RUNNING pid 9, uptime 0:11:02 server EXITED Feb 15 10:37 AM dockerfile FROM python:latest WORKDIR /root/django_scraper/ RUN apt-get update && apt-get install -y cron supervisor COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./app ./app COPY configs/supervisord.conf /etc/supervisor/conf.d/supervisord.conf COPY configs/cronfile /etc/cron.d/cronfile RUN crontab /etc/cron.d/cronfile ENTRYPOINT /usr/bin/supervisord cronfile # START CRON JOB LIST 0 12 * * * python /root/django_scraper/app/scrap_file.py >> /tmp/postgres_dump.log 2>&1 0 13 * * * python /root/django_scraper/app/db_dump.py # END CRON JOB LIST my repo https://github.com/yurakomarnitskyi/django-scraper dockerfile FROM python:latest WORKDIR /root/django_scraper/ RUN apt-get update && apt-get install -y cron supervisor COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./app ./app COPY configs/supervisord.conf /etc/supervisor/conf.d/supervisord.conf COPY configs/cronfile /etc/cron.d/cronfile RUN crontab /etc/cron.d/cronfile ENTRYPOINT /usr/bin/supervisord cronfile # … -
Embedded link displays when hardcoded but not when passed as variable
I have the following problem in my django project when trying to display an embedded google maps link in my page. This works (renders the Google Maps iframe with a populated map) when I hardcode the src URL but not when I pass it in my context even though they result to the same text string. This is my html detailview.html: {% if maps_link is not None %} <iframe src="https://maps.google.com/maps?q=-28.4457436,21.268374&hl=en&z=14&amp;output=embed" loading="lazy" referrerpolicy="no-referrer-when-downgrade" ></iframe> {% endif %} The src URL as it is shown above displays as I want it to, but when I do the following: {% if maps_link is not None %} <iframe src="{{ maps_link }}" <!-- This gets blocked --> loading="lazy" referrerpolicy="no-referrer-when-downgrade" ></iframe> {% endif %} then my browser gives me the following warning: To protect your security, www.google.com will not allow Firefox to display the page if another site has embedded it. To see this page, you need to open it in a new window. This is my views.py where the context is generated. I tried to get around it by applying xframes exemptions but that made no difference: from django.views.decorators.clickjacking import xframe_options_exempt from django.http import Http404, HttpResponse @xframe_options_exempt def detail(request, database_reference): context = { "content" : … -
Is there a way to upload file in django database from reactjs form
I have a problem with the form data. It says the submitted data is not a file type when I want to post data from React to Django models. I try to upload file with form .I used multipart/form-data in react component and also tried append file, and post it with axios. -
Django-nested-admin has no classes
I installed django-nested-admin, but it doesn`t work. I did it correctly first of all i added to settings py to INSTALLED APPS. then i imported it to admin py. but it didn`t work. What I have to do to solve this problem. does anyone help me? -
Django DRF not releasing memory after large response data is send to the front end
I am using Django rest framework in our application's backend. In one of the api end points we have to send a large data as response. So the orm and serialization functionalities takes about 400mb to send the data to the front end. I am using memory_profiler and when we call another api or the same api it shows 400mb at start and then an additional 400mb is used if the same endpoint is called. So total 800mb. It keeps on adding whenever we call the api till it crashes. This is my code ---> **views.py ** @api_view(["GET"]) @hasValidToken def get_all_session_messages(request, user, identity_data, *args, **kwargs): try: return chat_services.get_all_session_messages( user.id, kwargs["session_id"], ) except Exception as exc: return error(message=str(exc)) **services.py ** def get_all_session_messages(user_id, chat_session_id): try: query_responses = chat_repository.get_all_query_response_given_chat_id( chat_session_id ) return ok( message="Successfully retrieved all chat session messages", response_data=query_responses, ) except Exception as exc: raise Exception( "Error retreiving chat session messages in repository " + str(exc) ) **repository.py** def get_all_query_response_given_chat_id( chat_id, limit=None, order_by_created_at=False ): if not order_by_created_at: if limit is not None: query_responses = QueryResponseTracking.objects.filter(chat_id=chat_id)[ :limit ] else: query_responses = QueryResponseTracking.objects.filter(chat_id=chat_id) else: if limit is not None: query_responses = QueryResponseTracking.objects.filter( chat_id=chat_id ).order_by("-created_at")[:limit] else: query_responses = QueryResponseTracking.objects.filter( chat_id=chat_id ).order_by("-created_at") return QueryResponseTrackingSerializer(query_responses, many=True).data **serializers.py** … -
ThreadPoolExecutor from concurrent.futures module of Python for DRF appliction
I have simple GET Project API, The following is my code approach ` class ProjectListCreateView(generics.ListCreateAPIView): queryset = Project.objects.filter(is_deleted=False) serializer_class = ProjectSerializer def convert_to_json(self, state): return State.convertProjectObjectToJSON(self, state=state) def get(self, request, *args, **kwargs): try: objects = self.get_queryset() with ThreadPoolExecutor(max_workers=8) as executor: json_response = list(executor.map(self.convert_to_json, objects)) response = response_body(status_code=status.HTTP_200_OK, data=json_response) return Response(response, status=status.HTTP_200_OK) except Exception as e: response = response_body(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, data={str(e)}) return Response(response, status=status.HTTP_500_INTERNAL_SERVER_ERROR)` This APIs taking 970ms for 200 Projects. My question is Is this depends on the Threads so What should I need to deploy it on azure, do I have to make any changes regarding server configs or something else? -
react+django questions about https(SSL certificate)
I created a website using react and django. React was used as a front-end, Django was used as a back-end.(React uses S3, and Django uses EC2 server.) I was asked to adapt the website to HTTPS. I know I need to use SSL certificate. However, the front-page running on S3 can use and SSL certificate, so HTTPS is applicable, but the server running on EC2 can't use an SSL certificate. Because EC2 uses IP address, not useing Domain address. There are times when I need to make an API call to "http://my_ip_address/~" on the my website, but it keeps getting blocked. Please help me. How should I solve it? Do I need to add another Domain address to the EC2 server......? Or Is there a way to make a request from HTTPS to HTTP using CORS? I really need your help....! I applied SSL certificate to S3(front-page). But EC2 server is still HTTP. Django "settings.py" file : ... CORS_ALLOW_ALL_ORIGINS = True ... I also applied the above settings.