Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render a dictionary passed as Django Form Class parameter
I've got a template that renders two predefined forms depending on two different POST requests handled by a single view method to keep just one URL end point for the whole interaction. Form one doesn't take any parameters but form two does take an external API response a one. How can render the dictionary contents of that response as choice fields in form two class? view.py from django.shortcuts import render, HttpResponse from django.template import loader from .forms import QuestionForm, QuestionLevelForm from urllib import urlopen def process_question(request): if 'level' in request.POST: url = 'http://opentdb.com/api.php?amount=1&category=9&type="multiple"&level=' url += request.POST["level"] try: response = urlopen(url) except URLError as e: if hasattr(e, 'reason'): HttpResponse('Reaching server failed: ', e.reason) elif hasattr(e, 'code'): HttpResponse('Couldn\'t fufill request', e.code) else: question = response["results"][0] # API response passed to Form class instance as parameter form = QuestionForm(question) return render(request, "log/question.html", {"question": question, "form": form}) elif 'answer' in request.POST: return HttpResponse('NOT IMPLEMENTED: Check answer') else: form = QuestionLevelForm(); return render(request, "log/question.html", {"form": form}) forms.py from django import forms from django.forms import widgets class QuestionLevelForm(forms.Form): choices = (('', '---Please choose a level---'), ('easy', 'Easy'), ('medium', 'Medium'), ('hard', 'Hard')) label = forms.CharField(label="Choose your question level") select = forms.CharField(widget=forms.Select(choices=choices)) class QuestionForm(forms.Form): # Gets question dictionary … -
HTML Modals Intertwined on click action, should be separate
I have two modals on a single HTML template. When I implemented the second modal, the first one became tied to its actions and I want them to be separate. When I click the button to add time, I want the just the time form modal to show. When I click a user, I want some of their profile details shown on the right of the page. As of now, when I click the 'add time' button, they now stack together. Here is a picture of the issue: You can see that the front modal covers the form behind, I want these to be separate actions. When I click a button to add time, just this modal form should show: When I click on a user button, just this modal should show on the right hand page: Here are my button HTML: <button class="btn btn-danger add-btn mb-0" data-bs-toggle="modal" data-bs-target="#timetrackModal"><i class="ri-add-line align-bottom me-1"></i> Add Time Entry</button> <button type="button" class="btn py-0 fs-16 text-body" id="settingDropdown" data-bs-toggle="dropdown"> <i class="ri-stack-line"></i> </button> <a href="#userProfileCanvasExample{{tech.pk}}" class="avatar-group-item" data-bs-toggle="offcanvas" data-bs-trigger="hover" data-bs-target="#userProfileCanvasExample{{tech.pk}}" aria-controls="userProfileCanvasExample{{tech.pk}}" title={{tech.username}}> <div class="rounded-circle avatar-xs"> <div class="avatar-title rounded-circle bg-info"> {{tech.username|first}} </div> </div> </a> Here is the Modal HTML: <div class="modal fade zoomIn" id="timetrackModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog … -
TypeError: BaseMiddleware.__call__() missing 2 required positional arguments: 'receive' and 'send'
I am getting the above error for my custom middleware which i created also it's not revoking when i am trying to do so from GOVDairySync.exceptions import * from channels.middleware import BaseMiddleware from rest_framework.authtoken.models import Token from django.contrib.auth.models import AnonymousUser from channels.db import database_sync_to_async def get_user(token): try: token = Token.objects.get(key=token) return token.user except Token.DoesNotExist: return AnonymousUser() class TokenAuthMiddleware(BaseMiddleware): async def _call_(self, scope, receive, send): headers = dict(scope['headers']) if b'authorization' in headers: token_name, token_key = headers[b'authorization'].decode().split() if token_name == 'Token': try: print(token_key) # Try to get the user using the token scope['user'] = await get_user(token=token_key) print(scope['user']) except BaseCustomException as e: # If an exception occurs, send an error response to the client response = { 'type': 'authentication.error', 'message': str(e), } await send({ 'type': 'websocket.close', 'code': 400, # Custom code for authentication error 'text': 'Authentication error', }) return await super()._call_(scope, receive, send) above code block is the custom middleware which i created, how can i solve the issue? i want to use ths middleware as below from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application from chat_app import routing from channels.auth import AuthMiddlewareStack from .tokenauth_middleware import TokenAuthMiddleware # new application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( TokenAuthMiddleware(URLRouter(routing.websocket_urlpatterns)) … -
Django query doesn't return the instance that I just saved in database
I'm working on a project that requires to trace the events related to a process. In my case I have Registration and RegistrationEvent models with the latter connected throug a ForeignKey to Registration. I also have written a method of RegistrationEvent called _ensure_correct_flow_of_events which prevents from adding Events in an order that doesn't make sense and is called when model.save is called. Infact the flow of events must be SIGNED -> STARTED -> SUCCESS -> CERTIFICATE_ISSUED. At any moment the event CANCELED can happen. In order to evaluate event sequence this method calls another method _get_previous_event which return the last event registered to Registration. After a SUCCESS event is created, the save method calls Registration.threaded_issue_certificate which is a method that should create a certifcate and after that create a CERTIFICATE_ISSUED event in a new thread, in order to process the response fastly. Problem is when CERTIFICATE_ISSUED is about to be created _ensure_correct_flow_of_events and _get_previous_event are called and at this point _get_previous_event does not return the just created SUCCESS event but the previous STARTED event. My log is Checking correct flow, previous event: Course started - admin registration id: 1 current event_type: 3 Checking correct flow, previous event: Course started - … -
Django - Displaying Primary key in the HTML Modal form
I am new to Django, I want to display table data to Modal html form but it always shows the 1st record on Modal form. For e.g. in the image below, I have clicked on 43. TEST - 4, 43 is the primary key, I want to display the primary key in the Modal title, But the Modal title shows the primary key 41 which is 1st record. Here is the HTML code Waara List as of - {% now "jS F Y" %} Pending Waara's Waara already given {% for i in dictTask %} {{i.pk}} - {{i.firstname}} - {{i.lastname}} - {{i.phonenumber}} Mark as Done PRIMARY KEY {{i.pk}} × ... Close Save changes {% endfor %} </div> I was expecting correct Primary Key -
TypeError: Field 'id' expected a number but got <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x000001C1939EBE90>>
When I try add the product to wishlist it gives me above error, It still saves the object to model def plus_wishlist(reques): if request.method == "GET": prod_id = request.GET.get('prod_id') product = Product.objects.get(id=prod_id) ruser = request.user wishlist = Wishlist.objects.create(user=ruser, product=product) wishlist.save() return JsonResponse({'message': 'Added to Wishlist.'}) Also when i try to use ruser=request.user.id ValueError: Cannot assign "1": "Wishlist.user" must be a "User" instance. -
Custom Select Input With Search on the Frontend
See example here... Hello! The only thing i want to achieve here, is when you click (focus) on that input, automatically appears right below a "customized select popup" where apart from selecting an option, you can select a link and see the results quantity shown at the bottom of the select. Here is my example All i did was a select input with an input search to recreate this. but this is not as scallable as the other example. Im way more experienced with backend, thats why im having this type of issues with the front.... Im using in the frontend just HTML CSS and Vanilla JS. Backend with Django... Any suggestion? -
Python Django no such table: app_db
File "C:\python\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\python\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\python\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\python\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\python\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\python\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) File "C:\python\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\python\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\python\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: app_db I tried python manage.py migrate runserver makemigrations and migrate bu it diddnt work i just delete sqlite and this happened -
Can Django handling multiple id in one view?
In order to do exercises in Django 4.2 and Python, I am creating a project in Django so that users can consult and evaluate the books they read. Some books are already in the database in the "Book" table in the "library" app. My goal is for users to add these books to their user area, which would be saved in the "UserBook" table of the "readers" app so that they could later add notes, or classification. To implement this logic, the idea is for the user to search for a book, if it exists in the "Book" database of the "library" app, enter the book page and use the button "Add to my books" it is automatically added (its copied data) to the "Userbook" table in the "readers" app and is displayed on the book page in the user area. (https://i.stack.imgur.com/0kB1m.png) This is the table "Book" of the app "library" enter image description here This is the code for the url path('book/int:id/', views.single_book, name='single_book'), that have the form and the button "Add to my books". (https://i.stack.imgur.com/oTntg.png) This is the table "UserBook" of the app "readers" (https://i.stack.imgur.com/Wx9C4.png) This is the view for the page that presentes the book in the … -
I don't understand how c react integration works on django
I have a problem integrating the react project with django online (host server), but there are no problems with local servers, everything works fine on react I can upload it to netlify or vercel but I don't understand what to do with django need to upload my project to the internet for free like netlify, versal, etc Please help me I tried to upload the react project to django somehow, but the problem there is that the static path does not find html, maybe because the path is not correct there, or when I registered npm run build on the react, there was a static folder and somehow django addressed him, I don't understand -
Preventing Data Tampering in HTTPS Requests: Safeguarding User-Initiated Donations
Could a Man-in-the-Middle (MITM) attack compromise the integrity of user-initiated transactions over HTTPS? Specifically, if a user selects an amount to donate on a website, is it possible for a hacker to intercept and modify the donation amount?If yes, what strategies can be implemented to safeguard against unauthorized alterations and ensure the security of transactions conducted over HTTPS? note: I'm using django in development. -
I get the admin id but when im logged in as a user i still get admin id when i try to fetch the user id
i created a function in my views.py file which lets you see different dashboards according to the role of the email which is logging in now when im trying to fetch the id of user im getting the id of the user which was loggod on the server before what chnages should i be doing for this.I tried clearing the session during logout but it's still not working and the code is fetching me the id of previous logged in admin. def determine_role(request): user = request.user # Get the authenticated user object role = user.role # Access the role attribute # Now you can use the role to perform further actions if role == 'admin': # If the user is an admin, do something return render(request, 'loginapp/admin_dashboard.html') elif role == 'user': # If the user is a regular user, do something else return render(request, 'loginapp/user_dashboard.html') -
Trouble Connecting Django Application to PostgreSQL Database Running in Docker Container
I'm currently working on a Django project where I'm using a virtual environment (venv) to run Django locally on my machine (Windows). Additionally, I have a PostgreSQL database running in a Docker container. I'm encountering issues trying to establish a connection between my Django application and the PostgreSQL database. Whenever I attempt to run python manage.py makemigrations, I get the following error: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "host.docker.internal" (141.31.78.207), port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections? warnings.warn( No changes detected Here are the relevant portions of my Django settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'SilverSurfer', 'USER': 'postgres', 'PASSWORD': "root", 'HOST': "host.docker.internal", 'PORT': '5432', } } And here's my Docker Compose file: version: "3.9" services: db: image: postgres:15.0 environment: POSTGRES_DB: SilverSurfer POSTGRES_USER: postgres POSTGRES_PASSWORD: root ports: - "5432:5432" volumes: - ./db.sql:/docker-entrypoint-initdb.d/db.sql It's worth noting that my Docker container for the database is running: CONTAINER ID IMAGE COMMAND CREATED STATUS 528ad4e3232f postgres:15.0 "docker-entrypoint.s…" 37 minutes ago Up 37 minutes PORTS NAMES 0.0.0.0:5432->5432/tcp 02_db-db-1 I've tried connecting to the PostgreSQL database using psql, but I receive … -
How to add field with its data from one model to another one in Django?
Django already has a User model, which has a username field; I also have a Profile model. What I want to achieve is to send the username from the User model along with the fields of the Profile model, So that I can access the username from the Profile model itself , as to the frontend I'm returning an object of the Profile model MODELS User= get_user_model() class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() department= models.CharField(max_length=50,blank=True) degree= models.CharField(max_length=20,blank=True) year= models.CharField(max_length=20,blank=True) bio = models.TextField(blank=True) profileimg= models.TextField(default=DEFAULT_IMAGE_DATA) def __str__(self): return self.user.username SERIALIZER class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields=['id','user', 'id_user', 'department', 'degree', 'year', 'bio','profileimg'] class ChatMsgSerializer(serializers.ModelSerializer): reciever_profile= ProfileSerializer(read_only=True) sender_profile= ProfileSerializer(read_only=True) class Meta: model = ChatMsg fields=['id','user', 'sender','sender_profile', 'reciever','reciever_profile', 'msg', 'is_read', 'date'] One Solution I though Was to make another fetch request from the frontend and make one more endpoint that returns the username , but idts it would work well when i need both sender and reciever username -
How to reuse a model crated for crate too many model in Django?
I have model in models.py in my app Django : class Personnel(models.Model): id = models.AutoField(primary_key=True) card_number = models.BigIntegerField() name = models.TextField(db_collation='C') family = models.TextField(db_collation='C') height = models.TextField(db_collation='C', blank=True, null=True) weight = models.FloatField(blank=True, null=True) job_type = models.BigIntegerField(db_column='Job_Type', blank=True, null=True) age = models.FloatField(db_column='age', blank=True, null=True) Superviser_score = models.FloatField(db_column='Superviser_score', blank=True, null=True) QC_score = models.FloatField(db_column='QC_score', blank=True, null=True) def __str__(self)-> str: return f'{self.card_number} - {self.family} - {self.name}' class Meta: managed = False db_table = 'personnel' And in admin.py: @admin.register(Personnel) class MyPersonelAdmin(admin.ModelAdmin): list_display = ['card_number','name','family','center','job_type'] How can I reuse personenel model for create too many model ? I try below code in models.py for crate another model but I get error: class SuperviserModel(Personnel): id=Personnel.id card_number = Personnel.card_number name = Personnel.name family = Personnel.family center = Personnel.center distance = Personnel.distance job_type = Personnel.job_type overtime = Personnel.overtime class Meta: managed = False db_table = 'personnel' Error: column personnel.personnel_ptr_id does not exist -
'Expected a value of type List<dynamic> but got one type _JsonMap'
The code below is displays my List<dynamic> casting method, yet when I preview my code, the info displayed is that 'Expected a value of type List<dynamic> but got one type _JsonMap'. My data is being retrieved from a django rest framework into a json format. I run server whenever I start the flutter app. // ignore_for_file: dead_code, prefer_const_constructors, prefer_const_literals_to_create_immutables, deprecated_member_use, avoid_print, non_constant_identifier_names import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:async'; Future<List<Data>> fetchData() async { var url = Uri.parse('http://127.0.0.1:8000/api/?format=json'); final response = await http.get(url); if (response.statusCode == 200) { // final jSon = "[${response.body}]"; List jsonResponse = (json.decode(response.body) as List<dynamic>); return jsonResponse.map((data) => Data.fromJson(data)).toList(); } else { throw Exception('Unexpected error occured!'); } } class Data { final int ID; final String visitor_name; final String visit_date; final String time_in; final String time_out; final String department; final String visitee_name; final String address; final String phone; final String purpose_of_visit; Data({required this.ID, required this.visitor_name, required this.visit_date, required this.time_in, required this.time_out, required this.department, required this.visitee_name, required this.address, required this.phone, required this.purpose_of_visit}); factory Data.fromJson(Map<String, dynamic> json) { return Data( ID: json['ID'], visitor_name: json['visitor_name'], visit_date: json['visit_date'], time_in: json['time_in'], time_out: json['time_out'], department: json['department'], visitee_name: json['visitee_name'], address: json['address'], phone: json['phone'], purpose_of_visit: json['purpose_of_visit'], ); } } class ViewRecord extends … -
Django: update one table based on another
I have two tables Table1 and Table2 with the same field hash_str. from django.db import models class Table1: data = JSONField(...) hash_str = CharField(...) class Table2: name = CharField(...) parsed = DateTimeField(...) hash_str = CharField(...) is_updated = BooleanField(...) # ... Sometimes i need to update Table2 instances based on Table1 instances with the same hash. But i want to use Table2.objects.bulk_update(...) for it. Because there is too much instances to update them one by one like this: # ... for t2_obj in Table2.objects.filter(is_updated=False): t1_obj = Table1.objects.get(hash_str=t2_obj.hash_str) t2_obj.name = t1_obj.data["name"] t2_obj.parsed = t1_obj.data["parsed"] t2_obj.is_updated = True t2_obj.save() # ... How can i do it properly? -
How to get realtime stdout from a celery task?
I have a Django project in which i'm running some background tasks with celery, one of my goal is to show real-time stdout of the running task so that the user can see the progress. the issue is that i get the stdout of the process only when it is finished executing (all is dumped at once). Views.py def run_script(request, file_type, file_id): run_features.delay(arguments) return Tasks.py @shared_task def run_features(arguments): process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) channel_layer = get_channel_layer() while True: output = process.stdout.readline() if output == '' and process.poll() is not None: break if output: print(output) async_to_sync(channel_layer.group_send)( 'output_group', { 'type': 'send_output', 'output': output.strip() } ) process.wait() return process.returncode Celery INFO -------------- celery@ritik v5.3.1 (emerald-rush) --- ***** ----- -- ******* ---- Linux-6.5.0-25-generic-x86_64-with-glibc2.35 2024-03-21 09:30:54 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: Automation:0x7e2bb4073280 - ** ---------- .> transport: redis://localhost:6379/0 - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery Expectation - I get the stdout, line by line, while the task is running. Actual result - I … -
Invalid block tag on line 2: 'endblock'. Did you forget to register or load this tag?
{% extends "base.html" %} {% block title %} Home {% endblock %} {% block content %} {% endblock %} Seems correct to me, but it's showing this error. -
Update only specific fields in a models.Model vDjango
I have model in models.py: class SuperviserModel(models.Model): name = models.TextField(db_collation='C') family = models.TextField(db_collation='C') score = models.FloatField(db_column='score ', blank=True, null=True) # def __str__(self)-> str: return f' - {self.family} - {self.name}' class Meta: managed = False db_table = 'personnel' And in admin.py: @admin.register(SuperviserModel) class MySuperviserModelAdmin(admin.ModelAdmin): list_display = ['name','family','score'] sortable_by = ['name','family'] search_fields=['name', 'family'] I want when superviser user edit personnel just update score field, And cant update name and family field. How can I do? -
Image is not displayed/loaded in my django website which i deployed on Cpanel
details of my code, in my settings.py i have: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') and this is how i tried to acces form the template: in very first page: % load static % to display image, <a class="navbar-brand" href="#"><img src="{% static 'images/main.png' %}" alt="imagetwo" width="100" height="50"></a> anyone who can help me please -
Having trouble configuring ssl for django apache2
I have two errors: 'AH00112: Warning: DocumentRoot [/etc/apache2/var/www/html] does not exist' while i runed this cmd: >>>> grep -r "DocumentRoot" /etc/apache2/ >>> /etc/apache2/sites-available/000-default.conf: DocumentRoot > var/www/html > >>> /etc/apache2/sites-available/amicom_com_vn.conf: DocumentRoot > /var/www/html > >>> /etc/apache2/sites-available/default-ssl.conf: DocumentRoot > /var/www/html when i run 'https://example.com' i see 'Apache2 Default Page' how can i fix this error, this is my config ssl <VirtualHost *:443> ServerAdmin webmaster@localhost ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/html SSLEngine on SSLCertificateFile /etc/ssl/certs/ca-certificates.crt SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key </VirtualHost> -
python exclude non accessible image with requests
i've written a really simple function with requests, wich with a giver url checks if it gets a response and if this response is an image. It actually works, but is crazy slow at times. i'm too inexperienced to understand why is that. How can i improve it or achieve the same thing in a better and faster way? def is_image_url(url): try: response = requests.get(url) status = response.status_code print(status) if response.status_code == 200: content_type = response.headers.get('content-type') print(content_type) if content_type.startswith('image'): return True return False except Exception as e: print(e) return False i'm using that function to exclude images who are not acessible, like images from instagram, facebook etc. i thoughtit could work fine because i actually need to check only 10 images that i get from google custom search api. for now i've excluded the function from the application, and tried do a similar thing with checking the image height or width to assure that it existed and was accessible without much success. -
Python Django dj-rest-auth AttributeError
I was trying the demo project ( https://dj-rest-auth.readthedocs.io/en/latest/demo.html ) and when I tried to login I got the error: Django 4.2.5 django-allauth 0.61.1 dj-rest-auth 5.0.2 PyJWT 2.8.0 Internal Server Error: /api/v1/social/google/login/finish/ Traceback (most recent call last): File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/views/decorators/debug.py", line 92, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/dj_rest_auth/views.py", line 48, in dispatch return super().dispatch(*args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/dj_rest_auth/views.py", line 125, in post self.serializer.is_valid(raise_exception=True) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/serializers.py", line 227, in is_valid self._validated_data = self.run_validation(self.initial_data) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/serializers.py", line 429, in run_validation value = self.validate(value) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/dj_rest_auth/registration/serializers.py", line 160, in validate login = self.get_social_login(adapter, app, social_token, token) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/dj_rest_auth/registration/serializers.py", line 62, in get_social_login social_login = adapter.complete_login(request, app, token, response=response) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/allauth/socialaccount/providers/google/views.py", line 82, in complete_login id_token = response.get("id_token") AttributeError: 'str' object has … -
I am running elastic search on 0.5-1 vCPU (1 shared core) GCP but the server is not able to handle how to fix this?
I am running Elasticsearch on 0.5-1 vCPU (1 shared core) with 1.7 GB of memory (GCP). When I start the elastic search service the server is crashed. How do we fix this issue? I am running Django with Postgres and Elasticsearch.