Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"The request is missing a valid API key."
Am making a web application that one can read books through the site. I want to use google drive to store my PDF files for the textbooks, and in my application the Drive should serve the pdfs on my site when one want to read a book, I am using drive API, but I keep on getting the ("The request is missing a valid API key.") error, am using Django. when I check the logs for my local server it is working([31/Dec/2024 13:17:54] "GET /books/9/link/ HTTP/1.1" 200 96), but on the browser the pdf is not served what should I do? enter code here drive/utils.py from google.oauth2 import service_account from googleapiclient.discovery import build from payments.models import Payment from django.utils.timezone import now from library.models import Book Path to your service account file SERVICE_ACCOUNT_FILE = 'BookShelf/credentials/vernal-segment-445921-k9-8c59294dc1a2.json' SCOPES = ['https://www.googleapis.com/auth/drive.readonly'] def create_service(client_secret_file, api_name, api_version, scopes): """ Create and return a Google API service instance. """ credentials = service_account.Credentials.from_service_account_file( client_secret_file, scopes=scopes ) return build(api_name, api_version, credentials=credentials) def initialize_drive_service(): """ Initialize and return the Google Drive service. """ return create_service(SERVICE_ACCOUNT_FILE, 'drive', 'v3', SCOPES) def generate_pdf_link(file_id): """ Generate a shareable link for a Google Drive file. :param file_id: The ID of the file on Google Drive … -
How to create GeneratedField with lookup from settings file?
While using Django 5.1, I'm trying to create a GeneratedField which should return True or False depending on which file has been uploaded. The model will accept both image- and video files. I want to do this in order to be able to filter on e.g. CampMedia.objects.filter(is_image=True). # models.py from django.conf import settings from django.db import models from django.db.models import Case, Q, When class CampMedia(models.Model): media = models.FileField(upload_to="camps") is_image = models.GeneratedField( expression=Case( When( condition=Q([Q(media__endswith=ext) for ext in settings.VALID_IMAGE_FILETYPES], Q.OR), then=True, ), default=False, ), output_field=models.BooleanField(), db_persist=True, ) # settings.py VALID_IMAGE_FILETYPES = ["png", "jpg", "jpeg", "gif", "webp"] This is what's generated in the migration file: # migrations/0007_image.py from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("camps", "0006_auto"), ] operations = [ migrations.AddField( model_name="campmedia", name="image", field=models.GeneratedField( db_persist=True, expression=models.Case( models.When( condition=models.Q( [ models.Q(("media__endswith", "png")), models.Q(("media__endswith", "jpg")), models.Q(("media__endswith", "jpeg")), models.Q(("media__endswith", "gif")), models.Q(("media__endswith", "webp")), ], "OR", ), then=True, ), default=False, ), output_field=models.BooleanField(), ), ), ] However, this generates this error when running python manage.py migrations: $ ./manage.py migrate camps Operations to perform: Apply all migrations: camps Running migrations: Applying camps.0007_image...Traceback (most recent call last): File "C:\xampp\htdocs\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Owner\.virtualenvs\p1pRKLs2\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\Owner\.virtualenvs\p1pRKLs2\Lib\site-packages\django\core\management\__init__.py", line 436, in execute … -
Convert a uploaded audio chunk to be playable in server
I have a hour long audio streamed to backend with websockets. I need to start transcribing the audio and give back response in near realtime. atleast prevent users from waiting an hr long before checking transcriptions. I have broken down the problem to below steps Record audio stream split stream to 30 second chunks and upload convert audio chunks to seperate files and transcribe send back transcribed text The problem i face is when i try to play the second chunk of audio i get Invalid data found when processing input error. It is unplayable and dosent seem to have any audio information associated with it. Is it possible to add audio information into the second chunk, since first chunk is plays fine. Frontend async startRecording() { this.isRecording = true; // Start WebSocket connection this.websocket = new WebSocket("URL"); this.websocket.onopen = () => console.log("WebSocket connected"); this.websocket.onclose = () => console.log("WebSocket disconnected"); this.websocket.onstop = () => console.log("WebSocket onstop"); this.websocket.onerror = (error) => { console.error("WebSocket error:", error); this.stopRecording (); }; this.websocket.onmessage = (event) => { console.log(event.data) }; const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); this.mediaStream = stream this.mediaRecorder = new MediaRecorder(stream, { mimeType: "audio/webm" }); // Send audio chunks in real-time this.mediaRecorder.ondataavailable … -
Django: Unable to Retrieve Phone Number from User's Latest CartOrder in Chatbot View
Problem: I'm building a chatbot using Django and I'm having trouble getting the phone number from my CartOrder model. I have a view called log_customer_query that's supposed to return the phone number of the user's latest order, but it's not working. Code: Here's my log_customer_query view: def log_customer_query(request): user = request.user query_text = request.POST.get('query_text', '') if not user.is_authenticated: return JsonResponse({'error': 'User must be authenticated to log a query.'}, status=401) try: # Fetch the latest order for the user latest_order = CartOrder.objects.filter(user=user).latest('order_date') # Create a new customer query new_customer = customer.objects.create( user=user, title=query_text[:100], # Limit to 100 characters pid=latest_order.pid, oid=latest_order.oid, full_name=latest_order.full_name, email=latest_order.email, mobile=latest_order.mobile, address=latest_order.address, landmark=latest_order.landmark, city=latest_order.city, state=latest_order.state, postalCode=latest_order.postalCode, images=latest_order.images, price=latest_order.price, old_price=latest_order.old_price, qty=latest_order.qty, color=latest_order.color, size=latest_order.size, order_date=latest_order.order_date, return_expire_date=latest_order.return_expire_date, product_status=latest_order.product_status, ) return JsonResponse({'success': 'Query logged successfully.'}) except CartOrder.DoesNotExist: # If the user doesn't have any orders, create a new customer query without order details new_customer = customer.objects.create( user=user, title=query_text[:100], # Limit to 100 characters ) return JsonResponse({'success': 'Query logged successfully.'}) And here's my CartOrder model: class CartOrder(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) sku = ShortUUIDField(length=10, max_length=100, prefix="sku", alphabet="1234567890") pid = ShortUUIDField(null=True, blank=True, default=None) oid = ShortUUIDField(length=10, max_length=100, prefix="oid", alphabet="1234567890") full_name = models.CharField(max_length=100, null=True, blank=True) email = models.CharField(max_length=100, null=True, blank=True) mobile = models.CharField(max_length=100, null=True, blank=True) address … -
Django's select_for_update(skip_locked=True) not compatible with spanning
I was attempting to lock the oldest item in a queryset and bashed my head over why it was not working. Every time I used this first code snippet the entire query set would be locked. with transaction.atomic(): locked_entry = Entry.objects.select_for_update(skip_locked=True).filter( event__date=distribution_date(), status='pending', entry_type__name='Premium' ).order_by('-created_at').first() print(locked_entry) sleep(4) However, upon passing the exact FK instances the lock began to correctly only lock the oldest instance. I'm sure it has something to do with how the SQL is called but was hoping for an explanation if there are any Django experts out there :) with transaction.atomic(): locked_entry = Entry.objects.select_for_update(skip_locked=True).filter( event=Event.objects.get(date=distribution_date()), status='pending', entry_type=EntryType.objects.get(name='Premium') ).order_by('-created_at').first() print(locked_entry) sleep(4) -
NGINX is not serving static files correctly
I'm having some trouble while trying to use nginx to serve my static files. What I'm trying to do is using nginx + gunicorn to deploy my django app, and I'm using docker compose to try to ease all needed conf. Here are my files: docker-compose.yml django_gunicorn: build: context: . volumes: - static:/app/static - media:/app/media env_file: - .env expose: - 8000 depends_on: db: condition: service_healthy networks: - app_network command: > gunicorn core.wsgi:application --bind 0.0.0.0:8000 --workers 3 --threads 2 # Serviço Nginx nginx: build: context: ./nginx volumes: - ./nginx/default.conf:/etc/nginx/conf.d/default.conf - static:/app/static django - Dockerfile FROM python:3.12-slim WORKDIR /app # Instala dependências do sistema RUN apt-get update && apt-get install -y \ build-essential \ libpq-dev \ default-libmysqlclient-dev \ && apt-get clean # Instala dependências Python COPY requirements.txt . RUN pip install --upgrade pip RUN pip install --no-cache-dir -r requirements.txt # Copia os arquivos do projeto COPY . . # Permissões para o entrypoint RUN chmod +x entrypoint.sh EXPOSE 8000 ENTRYPOINT ["sh", "./entrypoint.sh"] entrypoint.sh #!/bin/sh until python -c "import MySQLdb; MySQLdb.connect(host='${DATABASE_HOST}', port=int('${DATABASE_PORT}'), user='${MYSQL_USER}', passwd='${MYSQL_PASSWORD}', db='${MYSQL_DATABASE}')"; do sleep 1 done echo "Banco de dados disponível!" python manage.py migrate --noinput python manage.py collectstatic --noinput exec gunicorn --workers 4 --bind 0.0.0.0:8000 core.wsgi:application /nginx/default.conf location /static/ { … -
AssertionError: Class ProductSerializer missing "Meta.model" attribute although I have Meta() class with model attirbute
I'm trying to simply post data using this django serializer but I'm constantly receiving the error Class ProductSerializer missing "Meta.model" attribute. Do you know if I'm missing something: class ProductSerializer(serializers.ModelSerializer): class Meta: model : Product fields : ('title','image','likes') -
problem in getting user email in django app with sicial auth
hello i have a django e commerce app that have google social auth when new users create an account we create a some % of dicount code for them i have UserIdentifier class that when users create new account i save either their phoen number or their email address to then when a new users create account i check if we have this users before or not to stop them from abusing the discount code i have this pipeline : from django.contrib.auth import get_user_model, login from django.shortcuts import redirect from .models import Profile,UserIdentifier import re User = get_user_model() def save_profile(backend, user, response, *args, **kwargs): if backend.name == 'google-oauth2': email = response.get('email') first_name = response.get('given_name') last_name = response.get('family_name') unique_identifier = email user_exists_before = UserIdentifier.objects.filter(identifier=unique_identifier).exists() if not user_exists_before: UserIdentifier.objects.create(identifier=unique_identifier) # Update user fields if email: user.email = email if user.phone_number and not re.match(r'^\d{11}$', user.phone_number): user.phone_number = None user.first_name = first_name user.last_name = last_name user.save() # Update or create profile profile, created = Profile.objects.get_or_create(user=user) profile.first_name = first_name profile.last_name = last_name profile.email = email profile.save() # Handle login and redirection request = kwargs.get('request') # Get the request object from kwargs if request: user.backend = 'social_core.backends.google.GoogleOAuth2' login(request, user) # Log the user in regardless of … -
Django model foreign key to whichever model calls it
I am getting back into Django after a few years, and am running into the following problem. I am making a system where there are 2 models; a survey, and an update. I want to make a notification model that would automatically have an object added when I add a survey object or update object, and the notification object would have a foreign key to the model object which caused it to be added. However I am running into a brick wall figuring out how I would do this, to have a model with a foreign key which can be to one of two models, which would be automatically set to the model object which creates it. Any help with this would be appreciated. I am trying to make a model that looks something like this (psuedocode): class notification(models.model): source = models.ForeignKey(to model that created it) #this is what I need help with start_date = models.DateTimeField(inherited from model that created it) end_date = models.DateTimeField(inherited from model that created it) Also, just to add some context to the question and in case I am looking at this from the wrong angle, I am wanting to do this because both surveys and … -
Use the same logging.Handler in different main files
Cheers! I am developping a Django Projekt and I want to display my backend loggings to the forntend. Thats why i created a central logging Handler that pushes logs into a buffer. Every 20 sec my frontend sends a request to flush the buffer and display the log events. Central Loging Class (log.py): import logging class BufferedLogHandler(logging.Handler): def __init__(self): super().__init__() self.log_buffer = [] # Lokaler Puffer für Logs def emit(self, record): log_entry = self.format(record) # Format den Log-Eintrag self.log_buffer.append(log_entry) def create_external_log(self, level=None, timestamp=None, message=None): asctime = timestamp msg = message record = logging.LogRecord( level=level, msg=msg, asctime=asctime, lineno=0, exc_info=None, args=None, name= None, pathname="frontend", ) self.emit(record=record) return BufferedLogHandler.create_empty_response() def flush_buffer(self): logs_to_send = self.log_buffer[:] print(f'logs_to_send:{logs_to_send}') print("---------------------") self.log_buffer = [] return logs_to_send @staticmethod def create_empty_response(): response = {'message':""} return response buffered_handler = BufferedLogHandler() def setup_logger(bufferedHandler): # Den Logger holen (Root-Logger oder benannten Logger) logger = logging.getLogger() # Du kannst auch den Root-Logger verwenden # Setze das Log-Level (z.B. DEBUG, INFO) logger.setLevel(logging.DEBUG) # Erstelle einen Handler (z.B. für Konsole oder Datei) file_handler = logging.FileHandler('myapp.log') # Für eine Log-Datei # Erstelle ein Format für die Log-Nachrichten formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(filename)s - %(lineno)d - %(message)s') # Setze das Format für beide Handler bufferedHandler.setFormatter(formatter) file_handler.setFormatter(formatter) … -
Django ManyToMany through model/table indexing
For ManyToMany relationships Django will automatically create a trough model/table. For example for: class Magazine(models.Model): pass class Article(models.Model): magazines = models.ManyToManyField('Magazine', related_name='articles') there will be a Article.through manager and model. The associated table will have two separate indices for each of the columns. Two questions: How do I create a new index on both columns? I could run a raw SQL query to do it, but I wonder if there is a way to do something similar to how index_together, which is easy to maintain and track. Is there a reason why Django doesn't automatically add an index to both columns? In my test, I manually created the index and saw Postgres hit it a lot and gain performance. -
Django Project, browser not making HTTP GET request for static files in development server
Hello I’m trying to load my static files to my templates but they’re not getting passed to my browser. When I look at the developer tools, I don’t see my Javascript and HTML files being passed to the browser. For some reason when I make a request for the page that I'm trying to include the static files on, I get 'GET /login/ HTTP/1.1'. The browser isn't even making a request for the static files. When I enter in the URL for the static files such as domain/static/styles.css or domain/static/index.js, I get sent to the file and no issue occurs. It’s just for some reason when I enter the page that the static files should be included on, browser doesn’t make a request for the static files. -
Python/Django Dynamic Form creation
I have an html page, which have dropdown field. I had load dropdown values from DB. Now selecting dropdown, the required fields related to value may be load, which has been described in 1 DB Table. so how is it possible? I have done like this... class VenDocMastForm(forms.ModelForm): doc_cat = forms.ChoiceField( label='Document Type*', choices=[(0, 'SELECT')] + [(dt.doc_type_id, dt.doc_type_desc) for dt in ven_doc_mast.objects.all()], widget=forms.Select(attrs={'class': 'col-sm-12 form-control-sm dropdown'}) ven_doc_path = forms.FileField( label='Upload Document File', required=False, # This can be set to True if file upload is mandatory widget=forms.ClearableFileInput(attrs={'class': 'form-control btn-outline-primary'}) ) class Meta: model = ven_doc_hdr # Model used for saving data fields = [ 'doc_id', 'ven_id', 'doc_reg_no', 'doc_reg_dt', 'doc_last_dt', 'doc_reg_cat', ] widgets = { 'doc_id': forms.NumberInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'placeholder': 'Enter Document Type ID'}), 'ven_id': forms.TextInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'placeholder': 'Enter Vendor ID'}), 'doc_reg_no': forms.TextInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'placeholder': 'Enter Registration Number'}), 'doc_reg_dt': forms.DateInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'type': 'date'}), 'doc_last_dt': forms.DateInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'type': 'date'}), 'doc_reg_cat': forms.TextInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'placeholder': 'Enter Registration Category'}), } def save(self, commit=True): # Handle form saving to ven_doc_hdr instance = super().save(commit=False) # Save ven_doc_dtl entry if file is uploaded if self.cleaned_data.get('ven_doc_path'): ven_doc_dtl_instance = ven_doc_dtl( doc_id=instance.doc_id, ven_doc_type_id=instance.doc_id, # Example: Mapping the document type ID from … -
Best Practice for Creating a Model's Record in `post_save` Signal While Maintaining Data Integrity in Django
I am working on a Django application where I need to automatically create a Setting record with default values whenever a new User is created. My current implementation uses the post_save signal of the User model to handle this logic. from django.db.models.signals import post_save from django.db import transaction from django.contrib.auth.models import User from myapp.models import Setting @receiver(post_save, sender=User) def create_default_setting(sender, instance, created, **kwargs): if created: transaction.on_commit(lambda: Setting.objects.create(user=instance)) I used transaction.on_commit to make sure that the creation of the Setting record happens only after the User creation transaction is committed, to avoid issues where the User instance might not yet exist in the database. However, this separates the Setting creation from the User creation transaction. If for any reason the Setting creation fails (e.g., validation errors, database issues), I end up with a User record without a corresponding Setting, which violates data integrity. On the other hand, if I don't use transaction.on_commit and create the Setting directly in the post_save signal, there is a risk of attempting to create a Setting record before the User instance is fully saved in the database, or creating a Setting even when the User creation fails due to an uncommitted or rolled-back transaction. This leaves … -
Proper approach to login user in Django channels websockets?
Developing a dashboard using Django channels, two different consumers are implemented, UserConsumer and RequestConsumer. In UserConsumer methods like login, logout and get_user are implemented. The user Authentication is being done using OTP code sent to user mobile so that a user_send_code method is in charge of sending SMS while the user_login method verifies the code sent by user. UserConsumer is implemented as follow: class UserConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() async def receive_json(self, content=None, **kwargs): action = content.get("action", "user.get_user") if action == "user.login": await self.user_login(content) elif action == "user.send_code": await self.user_send_code(content) elif action == "user.logout": await self.user_logout() else: await self.user_get_user() async def user_send_code(self, content): await self.send("we will send sms to: {}".format(content['mobile'])) if check_mobile_pattern(content["mobile"]): code = random.randint(1111, 9999) self.scope[VERIFY_CODE] = code self.scope[MOBILE] = content["mobile"] result = await send_sms(content["mobile"], code) if result: await self.send_json(send_code(200)) else: await self.send_json(send_code(400)) else: await self.send_json(send_code(SystemErrorCodes.InvalidMobilePattern)) async def user_get_user(self): if self.scope['user'].is_authenticated: await self.send_json({"id": self.scope['user'].id}) else: await self.send_json(send_code(SystemMessageCodes.AnonymousUserMessage)) async def user_login(self, content): verify_code = self.scope.get("verify_code") code = content.get("code") mobile = self.scope.get(MOBILE) if mobile is not None and verify_code is not None and code == verify_code: user = await load_user_by_mobile(mobile) del self.scope[VERIFY_CODE] # login the user to this session. await login(self.scope, user) # save the session (if the session backend … -
Django app failing to get deployed on Azure web service
I have a Django app that was running without issues till 2 days back on Azure. I then added some Azure OAI code using semantic-kernel and since then haven't been able to complete the deploy step of github actions workflow to deploy the app. To use semantic-kernel, I had to update to python 3.11 from python 3.8 on Azure. The deployment runs for about 40 mins and then errors out. From docker logs, I see the following issue:ModuleNotFoundError: No module named 'django' 2024-12-30T01:12:32.6106267Z Using packages from virtual environment antenv located at /home/site/wwwroot/antenv. 2024-12-30T01:12:32.6117557Z Updated PYTHONPATH to '/opt/startup/app_logs:/home/site/wwwroot/antenv/lib/python3.11/site-packages' 2024-12-30T01:12:35.1840122Z [2024-12-30 01:12:35 +0000] [84] [INFO] Starting gunicorn 23.0.0 2024-12-30T01:12:35.3134084Z [2024-12-30 01:12:35 +0000] [84] [INFO] Listening at: http://0.0.0.0:8000 (84) 2024-12-30T01:12:35.3205313Z [2024-12-30 01:12:35 +0000] [84] [INFO] Using worker: sync 2024-12-30T01:12:35.3321195Z [2024-12-30 01:12:35 +0000] [89] [INFO] Booting worker with pid: 89 2024-12-30T01:12:35.4238708Z [2024-12-30 01:12:35 +0000] [89] [ERROR] Exception in worker process 2024-12-30T01:12:35.4473148Z Traceback (most recent call last): 2024-12-30T01:12:35.4475461Z File "/opt/python/3.11.10/lib/python3.11/site-packages/gunicorn/arbiter.py", line 608, in spawn_worker 2024-12-30T01:12:35.4476786Z worker.init_process() 2024-12-30T01:12:35.4477986Z File "/opt/python/3.11.10/lib/python3.11/site-packages/gunicorn/workers/base.py", line 135, in init_process 2024-12-30T01:12:35.4479379Z self.load_wsgi() 2024-12-30T01:12:35.4480603Z File "/opt/python/3.11.10/lib/python3.11/site-packages/gunicorn/workers/base.py", line 147, in load_wsgi 2024-12-30T01:12:35.4481752Z self.wsgi = self.app.wsgi() 2024-12-30T01:12:35.4484237Z ^^^^^^^^^^^^^^^ 2024-12-30T01:12:35.4485531Z File "/opt/python/3.11.10/lib/python3.11/site-packages/gunicorn/app/base.py", line 66, in wsgi 2024-12-30T01:12:35.4486749Z self.callable = self.load() 2024-12-30T01:12:35.4487911Z ^^^^^^^^^^^ 2024-12-30T01:12:35.4489069Z File "/opt/python/3.11.10/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line … -
How to Customize Indigo Theme and CSS Variables for Micro-Frontends in Open edX?
I’m working with Open edX, specifically using the Indigo theme and Micro-Frontends (MFEs). I want to customize the theme by setting CSS variables or tokens to maintain consistent branding across the platform. However, I’ve run into some challenges and am not sure how to proceed. My Setup: Open edX platform is hosted with the Indigo theme. I’m working with Tutor for managing the Open edX instance. The Micro-Frontends (React-based) are running on apps.local.edly.io. What I’ve Tried: I’ve looked into modifying the Indigo theme’s Sass variables (e.g., $primary-color) but couldn’t figure out the process to make these changes take effect. I don’t have React components inside the indigo-theme folder to directly manage styles or tokens for MFEs. I’ve come across mentions of the edx/brand package, but I’m unclear on how to use it to integrate the custom styles with MFEs. Questions: How can I customize the Indigo theme to define CSS variables or tokens? Is it possible to ensure these customizations are applied across both the core platform and the MFEs? If yes, what’s the best way to do this? Do I need to modify or replace the edx/brand package for this, and how do I integrate it properly with Tutor-managed … -
Websocket 404 error after deploying to the domain
I setup websockets (chat module) in my Django application, it is working fine on my local machine but when I deployed my app to amazon ec2 instance with containerization it says 404 Not Found while testing via the postman. My ASGI container logs also say the same: WARNING Not Found: /chat/1/ IP:47942 - - [XX:XX:XX] "GET /chat/1/" 404 4479 Note that there is no problem with Docker containers - I tried on containers too on my local machine, and it worked. I have asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cruze_development.settings') application = get_asgi_application() from cruze_development.middleware import JWTAuthMiddleware from cruze_development.consumers import ClubFeedConsumer, RideLocationConsumer application = ProtocolTypeRouter({ "http": application, "websocket": JWTAuthMiddleware( URLRouter([ path('ws/chat/<str:room_name>/', ClubFeedConsumer.as_asgi()), path('ws/location/<str:ride_id>/', RideLocationConsumer.as_asgi()), ]) ), }) wss://mydomain.com/ws/chat/1/ I am trying with both ws and wss Help me solve it, man! -
ODBC Driver 18 Heroku Django connection
I have database (Azure SQL) which I need to interact with on my Django backend and also I do have credentials like client id, client secret, tenant id. So basically I'm connecting via Azure App to this database. I run into a problem when Heroku on its side doesn't have ODBC Driver 18 installed so I followed https://github.com/matt-bertoncello/python-pyodbc-buildpack the buildpack which pre-installs ODBC Driver 17 however I faced another issue with that where my openssl version is 3.0 or something but it requires maximum of 1.1, anyway if this issue is settled I still left with ODBC Driver 17 version which makes impossible to connect via Azure APP credentials, so only ODBC Driver 18 would work for me. My question is simple, does anyone tried to do the same with heroku and Azure SQL, can you just share steps you take to connect to this database, also are you using VPN for backend? Cuz it seems like proxies can't handle the connection for db as well. Lmao, so many questions asked sorry about that, hope to find the answer here. Stackoverflow seems to be almost empty on that sort of questions, read around 10 posts related to this topic none … -
SSL: CERTIFICATE_VERIFY_FAILED when submitting forms in Django run on Windows VPS with Apache web server
I have a Django website hosted on a VPS (OS Windows server 2019). The web server is Apache 2.4 and Python version is 3.12.8. A Digicert SSL certificate successfully installed and the website is working in production under https. However, I get this error when I try to submit a login or signup form from the website in production: URLError at /login-page/ <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)> Here is the complete error traceback: URLError at /login-page/ <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)> Request Method: POST Request URL: https://www.mywebsite.com/login-page/ Django Version: 5.0.6 Exception Type: URLError Exception Value: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)> Exception Location: C:\Python 3.12.8\Lib\urllib\request.py, line 1347, in do_open Raised during: users_authentication.views._wrapped_view Python Executable: C:\Apache24\bin\httpd.exe Python Version: 3.12.8 Python Path: ['C:\\Apache24\\htdocs\\project', 'C:\\Python 3.12.8\\python312.zip', 'C:\\Python 3.12.8\\DLLs', 'C:\\Python 3.12.8\\Lib', 'C:\\Apache24\\bin', 'C:\\Python 3.12.8', 'C:\\Python 3.12.8\\Lib\\site-packages'] C:\Python 3.12.8\Lib\urllib\request.py, line 1344, in do_open h.request(req.get_method(), req.selector, req.data, headers, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … C:\Python 3.12.8\Lib\http\client.py, line 1336, in request self._send_request(method, url, body, headers, encode_chunked) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … C:\Python 3.12.8\Lib\http\client.py, line 1382, in _send_request self.endheaders(body, encode_chunked=encode_chunked) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … C:\Python 3.12.8\Lib\http\client.py, line 1331, in endheaders self._send_output(message_body, … -
Account Merging with Google Login and Normal Registration
In my Django project, I have both normal registration and Google login. If a user registers normally and provides their email, and then tries to log in with Google using the same email, the classic login screen appears. What I want is this: If a user logs in with Google first and then tries to log in with the same email via normal registration, or if they register normally and later try to log in with Google using the same email, I want both methods to lead to the same account. In other words, regardless of whether they log in with Google or normal registration, the user's information should be merged and they should access the same account in both cases. socal login sections in settings.py: SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '<722444511487-2i7e9u3urlugcp2cp6slp09jjg7kgdg3.apps.googleusercontent.com>' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '<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>' SOCIALACCOUNT_LOGIN_ON_GET=True ACCOUNT_UNIQUE_EMAIL = True EMAIL_VERIFICATION_METHOD = 'email' # settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 # TLS GENELLİKLE 587 PORTUNU KULLANIR SSL İSE GENELLİKLE 465 PORTUNU KULLANIR EMAIL_USE_TLS = True # TLS SSL'E GÖRE DAHA MODERN VE GÜVENLİDİR EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' views.py: def loginUser(request): if (request.user.is_authenticated): messages.error(request,"Giriş Yapılıyken Giriş Yapamazsın!") return redirect("index") form = LoginForm(request.POST or None) if (form.is_valid()): login(request,form.cleaned_data["user"]) messages.success(request,"Başarıyla Giriş … -
How to move django models to new server
I have two options and not know which is the best: 1 - After coping Django files, delete migration files, so after makemigrations and migrate tables will be created. And after that import dumped database (only data). or 2 - Import dumped database (full), everything (create tables and data). -
I got this error while solving some issues in my project
Traceback (most recent call last): File "C:\Users\hp\Downloads\examination-project-repo\Online-Examination-System-CUH-2024\admin\files.py", line 1, in from rest_framework.authtoken.models import Token File "C:\Users\hp\Downloads\examination-project-repo\Online-Examination-System-CUH-2024.venv\Lib\site-packages\rest_framework\authtoken\models.py", line 9, in class Token(models.Model): File "C:\Users\hp\Downloads\examination-project-repo\Online-Examination-System-CUH-2024.venv\Lib\site-packages\rest_framework\authtoken\models.py", line 15, in Token settings.AUTH_USER_MODEL, related_name='auth_token', ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\hp\Downloads\examination-project-repo\Online-Examination-System-CUH-2024.venv\Lib\site-packages\django\conf_init_.py", line 81, in getattr self.setup(name) File "C:\Users\hp\Downloads\examination-project-repo\Online-Examination-System-CUH-2024.venv\Lib\site-packages\django\conf_init.py", line 61, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting AUTH_USER_MODEL, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
'WSGIRequest' object has no attribute 'get' django 5.1.4
hey guys im new to django and in my first project i trying to save the cart of a visitor in session when i try to add some product in cart of session i have this error says < WSGIRequest object has no attribute 'get' i use a class for cart in my project and in init i check if 'cart' exists in session or no then create a key for 'cart' like this : in class Cart: class Cart: def __init__(self, request): """ Initialize The Cart """ self.request = request self.session = request.session cart = self.session.get('cart') if not cart: cart = self.session['cart'] = {} self.cart = cart # add a product to session cart: def add(self, product, quantity=1): """ Add The Specified Product To The Cart If Exists """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': quantity} else: self.cart[product_id]['quantity'] += quantity self.save() i also use another way for check if 'cart' exists in session: if 'cart' not in request.session: self.cart = self.session['cart'] = {} and still have the same issue... form for using the cart: class AddToCartProductForm(forms.Form): QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 30)] quantity = forms.TypedChoiceField(choices=QUANTITY_CHOICES, coerce=int, label=_('Quantity')) view: def add_to_cart_view(request, product_id): … -
I HAVE SOME QUESTION FOT PYTHON DJANGO ERROR
Django error Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON.How could i solve this error for website development when it return 500 error code. solution of bug for django developing