Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Access Checkout Session Metadata in Stripe Webhook for Payment Methods in Subscription Mode
I'm integrating Stripe Checkout in a Django application and handling webhooks to update user information based on payment events. However, I'm encountering issues accessing metadata associated with a Checkout Session when dealing with payment_method objects. Context: I have the following setup for Stripe Checkout: StripeCheckoutMonthlyView and StripeCheckoutYearlyView: Both create a Checkout Session with metadata (e.g., user_id, plan_type). Webhook Handler (stripe_webhook): Processes different event types from Stripe. Problem: In the payment_method.attached event, I need to access metadata that was included in the Checkout Session. However, the payment_method object does not include metadata and does not directly reference the Checkout Session. Here’s how my webhook handler looks: @csrf_exempt def stripe_webhook(request): payload = request.body event = None print('Stripe Webhook Received!') try: event = stripe.Event.construct_from( json.loads(payload), stripe.api_key ) except ValueError as e: # Invalid payload return HttpResponse(status=400) if event.type == 'payment_intent.succeeded': # Handle payment_intent.succeeded event pass elif event.type == 'payment_method.attached': payment_method = event.data.object # Issue: Payment method does not include metadata or session_id pass elif event.type == 'checkout.session.completed': session = event.data.object # Retrieve session metadata here pass else: print('Unhandled event type {}'.format(event.type)) return HttpResponse(status=200) What I Need: I need to update user information based on metadata that was included in the Checkout Session. Specifically: … -
How to get response content from a Response() object in a view decorator?
Let's say I have a decorator that can be applied to a DRF class based View. A basic version of the decorator i have is as follows:- `class LogRequest: def __init__(self, log_success=True, methods_to_log=None): self.log_success = log_success self.methods_to_log = methods_to_log if methods_to_log is not None else ["post"] def __call__(self, view_class): view_class.methods_to_log = self.methods_to_log view_class.log_success = self.log_success for method_name in self.methods_to_log: if hasattr(view_class, method_name): method = getattr(view_class, method_name) decorated_method = self.wrap_method(method) setattr(view_class, method_name, decorated_method) return view_class def wrap_method(self, method): @wraps(method) def wrapped_method(self, request, *args, **kwargs): method_name = request.method.lower() if method_name in getattr(self, "methods_to_log", []): log = Log(path=request.path, method=method_name) log.request_body = Log.parse_request_body(request) try: response = method(self, request, *args, **kwargs) except Exception as e: tb = traceback.format_exc() log.error_traceback = tb log.status_code = 500 log.response_body = str(e) log.save() return JsonResponse({"error": str(e)}, status=500) if self.log_success or response.status_code >= 400: log.status_code = response.status_code if 'application/json' in response.get('Content-Type', ''): response_content = response.rendered_content.decode("utf-8") log.response_body = response_content log.save() return response return method(self, request, *args, **kwargs) return wrapped_method` The problem is , when log_success is true and i want to log succesful responses or 400 errors, i am getting errors like JsonResponse' object has no attribute 'rendered_content' or 'Response' object has no attribute 'rendered_content' depending on what kind of response i … -
django authentication backend being ignored when specified
I have a two customer authentication backends: one for a standard login, and one for a two factor login. In my settings.py, I have them both listed AUTHENTICATION_BACKENDS = [ 'user_profile.auth_backends.TOTPBackend', 'user_profile.auth_backends.StandardLoginBackend', 'django.contrib.auth.backends.ModelBackend', ] I have them stored in the app folder (user_profile) in a file called auth_backends.py and the class names match: class TOTPBackend(ModelBackend): def authenticate(self, request, username=None, password=None, twofa_token=None, **kwargs): print("In TOTPBackend") # First, try to authenticate with the default method user = super().authenticate(request, username=username, password=password, **kwargs) if user is not None: ... And class StandardLoginBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): print("In StandardLoginBackend") # First, try to authenticate with the default method user = super().authenticate(request, username=username, password=password, **kwargs) if user is not None: ... Then I based on the view called from some logic, I want to explicitly call one or the other... class TwoFaLogin(APIView): permission_classes = (AllowAny,) def post(self, request): print("TwoFaLogin View") username = request.data['username'] passwd = request.data['password'] twofa_token = request.data['twofa_token'] user = authenticate(request, username=username, password=passwd, twofa_token=twofa_token, backend='user_profile.auth_backends.TOTPBackend') OR class StandardLogin(APIView): permission_classes = (AllowAny,) def post(self, request): print("StandardLogin View") username = request.data['username'] passwd = request.data['password'] user = authenticate(request, username=username, password=passwd, backend='user_profile.auth_backends.StandardLoginBackend') My challenge is that when making the authenticate call from the view, the backend parameter … -
Setting Manager for Django models dynamically
I'm trying to set my custom manager dynamically for given models. Here is a sample of my code class CustomManager(models.Manager): def active(self): return self.filter(name__startswith='c') def set_custom_manager(model_class, manager=CustomManager(), manager_name='objects'): setattr(model_class, manager_name, manager) return model_class class Facility(BaseModel): name = models.CharField(_("Name"), max_length=255) icon = models.ImageField(upload_to='location/facilities/') order = models.PositiveIntegerField(_("Order"), default=0) class Meta: verbose_name = _("Facility") verbose_name_plural = _("Facilities") ordering = ['order', 'id'] def __str__(self): return self.name set_custom_manager(Facility, CustomManager()) If I check manager class name of Facility instance, it's returning true >>> Facility.objects.__class__ <class 'apps.chargers.models.CustomManager'> But if I try to use default methods of models.Manager, it's returning error Facility.objects.all() Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.10/3.10.14/Frameworks/Python.framework/Versions/3.10/lib/python3.10/code.py", line 90, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File "/Users/njr/PycharmProjects/iwatt-backend/venv/lib/python3.10/site-packages/django/db/models/query.py", line 376, in __repr__ data = list(self[: REPR_OUTPUT_SIZE + 1]) File "/Users/njr/PycharmProjects/iwatt-backend/venv/lib/python3.10/site-packages/django/db/models/query.py", line 400, in __iter__ self._fetch_all() File "/Users/njr/PycharmProjects/iwatt-backend/venv/lib/python3.10/site-packages/django/db/models/query.py", line 1928, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/Users/njr/PycharmProjects/iwatt-backend/venv/lib/python3.10/site-packages/django/db/models/query.py", line 99, in __iter__ model_cls = klass_info["model"] TypeError: 'NoneType' object is not subscriptable -
API endpoing taking list as data in DRF
I have a class called Component in my models.py and I have an array of Component ids in React and I want to post them to my DRF API so I could get their data as my response. I want something like this: Request body: { compIds:[77,54,125], } Response: [ {id:77,name:"SMTH 77", price:120}, {id:54,name:"SMTH 54", price:140}, {id:125,name:"SMTH 77", price:61}, ] This is my Component model: class Component(models.Model): name = models.CharField(max_length=100) price = models.PositiveIntegerField() def __str__(self): return self.name class Meta: verbose_name = 'قطعه' verbose_name_plural = 'قطعات' I don't know how I should write my Serializer and my viewset. -
Django Websocket Failing right after handshake if using PostgresSql
I developed the application using Django and I used Django channels in it for messages. My websocket connections were working fine as soon as I was using my local db.sqlite3 but when I shifted to using PostgreSQL hosted on AWS RDS, I start getting connection error: HTTP GET /community/groups/5/ 200 [5.13, 127.0.0.1:1905] WebSocket HANDSHAKING /ws/group/5/ [127.0.0.1:1908] HTTP GET /AI/tools-list/ 200 [2.72, 127.0.0.1:1905] WebSocket DISCONNECT /ws/group/5/ [127.0.0.1:1908] WebSocket HANDSHAKING /ws/notifications/ [127.0.0.1:1913] WebSocket DISCONNECT /ws/notifications/ [127.0.0.1:1913] Disconnected with close code: 1006 Note: Sometime, my notification websocket gets connected but group chat websocket never gets connected I tried connecting to websocket but it keeps on failing -
"Error 404: The resource is not found on this computer" when deploy Django Web Service to Render.com, deployment is successful, site is Live w/green
I have a Django web application that works great when testing it in local server. It uses generics.APIViews, and there is no index.html file and no static files to be served. I've read and abided by all the Render.com docs to deploy to Render.com including https://docs.render.com/deploy-django and https://docs.render.com/web-services#port-binding. I suspect it has something to do with port binding. Been researching different ways to make it work. I'm new to Django so probably something simple I'm missing: Below a shot of my settings.py: import os import dj_database_url from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY', default='your secret key') # SECURITY WARNING: don't run with debug turned on in production! #DEBUG = True DEBUG = 'RENDER' not in os.environ ALLOWED_HOSTS = ['*'] RENDER_EXTERNAL_HOSTNAME = os.environ.get('RENDER_EXTERNAL_HOSTNAME') if RENDER_EXTERNAL_HOSTNAME: ALLOWED_HOSTS.append(RENDER_EXTERNAL_HOSTNAME) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'API' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'jproj.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': … -
Celery and Redis: Error: Invalid value for '-A' / '--app': Unable to load celery application. Module 'project' has no attribute 'celery'
Здраствуйте я пытаюсь подключить подключить асинхронные задачи через 'Celery' и брокер сообщений 'Redis'. Установил pip install celery создал файл celery.py рядом с settings.py и в нём прописал следующую конфигурацию import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.autodiscover_tasks(['accounts', 'shop']) Также, согласно рекомендациям из документации к Celery, добавил from .celery import app as celery_app all = ('celery_app',) Cоздал файл celery.py рядом с settings.py и в нём прописал следующую конфигурацию enter image description here import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.autodiscover_tasks(['accounts', 'shop']) Также, согласно рекомендациям из документации к Celery, добавил from .celery import app as celery_app all = ('celery_app',) C GitHab (https://github.com/microsoftarchive/redis/releases) скачал Redis-x64-3.0.504.zip распаковал и открыл файлы 'redis-server.exe' и 'redis-cli.exe' pip install redis и прописал в настройках проекта CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' Далее в терминале: py manage.py runserver И ввёл: celery -A project worker -l INFO --pool=solo Но терминал выводит ошибку: Usage: celery [OPTIONS] COMMAND [ARGS] Try 'celery --help' for help. Error: Invalid value for '-A' / '--app': Unable to load celery application. Module 'project' has no attribute 'celery' Есть знатоки которые сталкивались с подобным и … -
RecycleBin() got unexpected keyword arguments: 'title', 'content_type', 'object_id', 'deleted_by'
I have a recycle bin model in my Django project that works fine with other models since I have overidden the delete function to soft delete any model object by using is_deleted=True in every model. class RecycleBin(models.Model): title = models.CharField( max_length=1000, verbose_name="Title", null=False, blank=False, ) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() deleted_object = GenericForeignKey("content_type", "object_id") deleted_by = models.ForeignKey( "Accounts.User", verbose_name="Deleted By", on_delete=models.CASCADE, blank=False, null=False, related_name="deleted_by", ) tenant = models.ForeignKey( "Tenants.Tenant", verbose_name="Tenant", max_length=1000, null=False, blank=False, on_delete=models.CASCADE, ) date_deleted = models.DateTimeField(verbose_name="Date Deleted", auto_now_add=True) due_deletion_date = models.DateTimeField(verbose_name="Due Deletion", default=None, null=True, editable=False) However, in my Files model, when i try to delete a file, i get an error RecycleBin() got unexpected keyword arguments: 'title', 'content_type', 'object_id', 'deleted_by'. class AllFilesManager(models.Manager): def get_queryset(self): return super().get_queryset() class ActiveFileModelManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_deleted=False) class File(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=1000, null=False, blank=False) folder = models.ForeignKey( "Folders.Folder", on_delete=models.CASCADE, null=False, blank=False ) file = models.FileField( upload_to='tenants', storage=storage, max_length=1000, null=False, blank=False ) is_deleted = models.BooleanField(default=False, verbose_name="Is Deleted?") created_by = models.ForeignKey( "Accounts.User", verbose_name="Created By", on_delete=models.CASCADE, blank=False, null=False, related_name="file_created_by", ) modified_by = models.ForeignKey( "Accounts.User", verbose_name="Modified By", on_delete=models.CASCADE, blank=True, null=True, related_name="file_modified_by", ) tenant = models.ForeignKey( "Tenants.Tenant", verbose_name="Tenant", max_length=1000, on_delete=models.CASCADE, null=False, blank=False, ) date_created = models.DateTimeField(verbose_name="Date Created", auto_now_add=True) date_modified = models.DateTimeField(verbose_name="Date … -
Hosting React Frontend and Django Backend App in digital Ocean
Hi I'm trying to host React and django app in digital ocean apache server. When I do that successfully I get the Screen of Django rest framework as the page for the droplets IP address .I tried so many things but couldn't find a answer. Can someone tells me how to host django react app in digital ocean or namecheap shared hosting correctly Thanks In Advance. -
"PostgreSQL 12 or later is required (found 10.23)" Django error while connecting to PostgreSQL 16
Exception Type: NotSupportedError Exception Value: PostgreSQL 12 or later is required (found 10.23). The above exception is thrown by the db backend. The obvious assumption would a mismatch of versions; it isn't the case as I have made certain of this. The connection is to a remote db running on v16. Indeed, I have even migrated services but to no avail just to make sure. Also, it a bit imprecise as I was able to migrate, createsuperuser and create some objects from admins before the error was thrown again. settings/init.py: import os if os.environ.get("ENV_NAME") == 'production': from .production import * elif os.environ.get("ENV_NAME") == 'staging': from .staging import * else: from .base import * settings/base.py (contains base settings) import os from pathlib import Path import environ import dj_database_url env = environ.Env() # Take environment variables from .env file environ.Env.read_env() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # add ".parent" after creating new folder for settings PROJECT_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-uoo(9irb!fcd5w-t7z*ua2go84_g4)b8q&8ofw*c)dabqoaf12' # SECURITY WARNING: don't run with debug turned on in production! … -
Use AlpineJS data in django-cotton component
I'm trying to use AlpineJS jointly with django-cotton components. I tried the following but it did not work. <div x-data="{ message: 'I ❤️ Alpine' }"> <c-card x-bind:title="message" x-text="message"></c-card> </div> with django-cotton card component simply copied from django-cotton Quickstart. <div> <h2>{{ title }}</h2> <p>{{ slot }}</p> </div> Is there a way to achieve this? -
Need suggestions on getting data from odoo inside Django on user navigation
I am developing a Complaint Management System with the admin side in Odoo and the subscriber side in Django. All complaints and subscriber information are managed on the admin/Odoo side, while the Django side is used solely for subscriber registration and recording of complaints. I need suggestions on what technology or methodology to use to retrieve subscriber information from Odoo when a subscriber logs in. There are various links where subscribers can click to view their information, which is retrieved from Odoo. These options are coming in my mind XML-RPC read ().The simplest option is to read specific form data from Odoo and display it in a Django form when users click on certain links. Django Channels Observable. I Appreciate clear guidance which technology stack I should use. -
Django session is not maintained on browser. login_required decorator is redirecting to login page
Background: I made a custom user model in django with Custom backend implementing authenticate and get_user methods. its all working fine with the requests and the user objects and stuff, but when i tried to use login_required for a view, it sends the page back to login page. the user is being authenticated and all the stuff is happening. but login is not being maintained on the browser Github Link: https://github.com/WarLoRDlArS/Prodvi Login View: view is located in Prodvi/users/views.py def login_page(request): if request.method == "POST": pid = request.POST.get("pid") password = request.POST.get("password") if not Users.objects.filter(pid=pid).exists(): messages.error(request, 'Invalid Username') return redirect('users:login') user = authenticate(request, pid=pid, password=password) if user is None: messages.error(request, 'Invalid Credentials') return redirect('users:login') print("User is None") login(request, user) print("Login Successful") # Login is a success return redirect('home:index') # Test Login # pid: 000000 # password: abc return render(request, 'users/login.html') Index page code: index is located in Prodvi/home/views.py @login_required(login_url='users:login') def index(request): print("came here") return HttpResponse('Welcome To Prodvi') i tried with various stuff like changing session timeout, setting session_cookie_secure, debugging using print statements. when i remove login_require, it works but otherwise it doesnt. -
I'm having troubles migrating my company's data from Magento to Django Rest Framework
I observed that the SQL tables were not organised enough for a typical migration, so I decided to work on a new lighter DB and utilise Django because of its stability to handle the seeding of the new DB from the Magento DB through the API it provides. The major tables I need for the new DB are: Products Categories Brands Customer Details I have a script that successfully seeds categories and brands. I am yet to attempt Customer Details, and the major issue is that the products have images attached to them, and I am not sure how to do the migrations of images effectively. Also the categories are forgetting their parent category, reason is since they are all creating at the same time, the parent category ID will always return not found. I created some scripts already, seed categories and seed brands fully functional. I created another sript to run all the necessary migrations too. #!/bin/bash set -e GREEN='\033[0;32m' RED='\033[0;31m' RESET='\033[0m' GAP="\n\n\n" echo "Installing requirements..." pip install -r requirements.txt echo -e "${GREEN}Requirements installed!${RESET}${GAP}" echo "Migrating database..." python manage.py makemigrations python manage.py makemigrations helpers api python manage.py migrate echo -e "${GREEN}Migration complete!${RESET}${GAP}" echo "Seeding Image..." python manage.py seed_image echo … -
Django queryset stops working after multiple uses and filters
I am currently working on a task which requires me to divide my model data into multiple parts based on conditions and then process them differently. I am able to get data from my model correctly and check all available details that they exists. But after applying certain number of filters, suddenly the queryset stops working and don't give the correct results. I don't know why this is happening, can someone explain? Here is part of my code that is causing issue: def test_selection(): po_numbers = ( Model1.objects .filter(schedule__isnull=True) .filter(order_hold_type__isnull=True) .filter(so_line_status='Awaiting Supply') .values_list("customer_po", flat=True) .distinct() ) rows = Model1.objects.filter(customer_po__in=po_numbers).annotate( total_qty=Sum(F('line_item_quantity')*F('cup_count')) ).all() old_sizes = Sizes.get_old_sizes() old_po = rows.filter( item_size__in=old_sizes).values_list('customer_po', flat=True).distinct() rows = rows.filter(~Q(customer_po__in=old_po)).all() partially_scheduled = rows.filter( customer_po__in=list(rows.filter(schedule__isnull=False).values_list( 'customer_po', flat=True).distinct()) ).all() unscheduled = rows.filter( ~Q(customer_po__in=list(partially_scheduled.values_list( 'customer_po', flat=True).distinct().all())) ).all() model2_po = Model2.objects.values_list('customer_po', flat=True).distinct() g1 = unscheduled.exclude(customer_po__in=model2_po) po_list = g1.values_list('customer_po', flat=True).distinct() print(rows.count(), po_list) I thought the problem is in my flow so I created a separate function to test this and this is the point after which the problem starts occurring. This is not throwing any error but coming up empty and I have tried searching for anyone having similar issue but cannot find anything. I have tried following things uptil now: Use filter(~Q()) … -
Error: "libsecp256k1.so.0: cannot open shared object file" with pytonlib on Ubuntu
I'm running a Django project on Ubuntu, and I'm using the following requirements.txt: asgiref==3.8.1 bitarray==2.9.2 certifi==2024.8.30 cffi==1.17.1 charset-normalizer==3.3.2 crc16==0.1.1 crc32c==2.7.post1 Django==5.1.1 djangorestframework==3.15.2 idna==3.8 mysqlclient==2.2.4 pycparser==2.22 PyNaCl==1.5.0 pytonlib requests==2.32.3 sqlparse==0.5.1 tonsdk==1.0.15 tvm-valuetypes==0.0.12 tzdata==2024.1 urllib3==2.2.2 However, I’m facing the following error during runtime: {'msg': 'libsecp256k1.so.0: cannot open shared object file: No such file or directory', 'method': 'deposit'} Exception in tonlibjson.__del__: Traceback (most recent call last): File "/path/to/venv/lib/python3.12/site-packages/pytonlib/tonlibjson.py", line 133, in __del__ self._tonlib_json_client_destroy(self._client) AttributeError: 'TonLib' object has no attribute '_tonlib_json_client_destroy' Exception ignored in: <function TonLib.__del__ at 0x72e2b810da80> Traceback (most recent call last): File "/path/to/venv/lib/python3.12/site-packages/pytonlib/tonlibjson.py", line 136, in __del__ raise RuntimeError(f'Error in tonlibjson.__del__: {ee}') RuntimeError: Error in tonlibjson.__del__: 'TonLib' object has no attribute '_tonlib_json_client_destroy' Steps I’ve already tried: Installed libsecp256k1 using sudo apt-get install libsecp256k1-dev. Verified the installation with ldconfig -p | grep libsecp256k1, and the library is listed. Despite these steps, the error persists. It seems related to the pytonlib and possibly an issue with the TonLib class. Any help on resolving this error or further debugging steps would be greatly appreciated! -
django after submit login info, does not lead to intended detail view page
Thanks for takint the time. I don't know what to do here after a few days of trying differnt ideas. I am learning django, I had read many posts and tutorials, and finally came to this sets of code. After I submit the the prop login email and password, the page does not do anything. It just says "Invalid password" I am not sure my login view is connected to the sqllite. I am thinking my mistake is where the login view file, but not sure. I also use chatgpt to see if it can identify where the mistake is, but it didn't come up with anything. If anyone can point me where I need to adjust, would be much appricated. If I go to the address of the http://127.0.0.1:8000/user/2/, then, the page shows correctly. Unfortuanlly, the codes are long. Here are all the codes: views.py: import random from django.shortcuts import render from django.views.generic import (ListView, DetailView) from django.views.decorators.csrf import csrf_exempt from .models import CustomUser, Events from rest_framework.views import APIView from .serializers import CustomUserSerializer, EventsSerializer from rest_framework.response import Response from rest_framework import status from rest_framework.renderers import TemplateHTMLRenderer from django.contrib.auth import authenticate, login from django.contrib import messages from django.shortcuts import redirect, … -
how to receive webhooks events in django?
I have a webhook registered and have a php file that receives the message and dump it under text file. I want to achieve the same in django but the function never gets called when the event is triggerd the php code '' <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $input = file_get_contents('php://input'); $data = json_decode($input, true); file_put_contents('messages_log.txt', print_r($data, true), FILE_APPEND); $formatted_output = ''; $timestamp = date('d-M-Y-H:i'); if (isset($data['data']['message']['body_message']['content']) && !empty($data['data']['message']['body_message']['content'])) { $content = $data['data']['message']['body_message']['content']; $from_contact = isset($data['data']['message']['from_contact']) ? $data['data']['message']['from_contact'] : 'Unknown'; $formatted_output = sprintf("%s :: %s --> %s", $timestamp, $from_contact, $content); } else { $messages = isset($data['data']['data']['messages'][0]) ? $data['data']['data']['messages'][0] : null; if ($messages) { $message = isset($messages['message']) ? $messages['message'] : []; $content = isset($message['conversation']) ? $message['conversation'] : ''; $from_contact = isset($messages['verifiedBizName']) ? $messages['verifiedBizName'] : ''; if (!empty($content) && !empty($from_contact)) { $formatted_output = sprintf("%s :: %s --> %s", $timestamp, $from_contact, $content); } } } if (!empty($formatted_output)) { file_put_contents('formatted _messages_log.txt', $formatted_output . PHP_EOL, FILE_APPEND); } http_response_code(200); echo json_encode(['status' => 'received']); } else { http_response_code(405); echo json_encode(['status' => 'Method Not Allowed']); } ?> ''' So whenever I receive or send a message from whatsapp it gets dumped here with "messages_log.txt" Python django code (views.py) import os import json from django.http import JsonResponse from … -
Using specific Django LTS version with cookiecutter-django
Currently, the Cookiecutter Django template uses Django 5.0, which is not a long-term support (LTS) release. I couldn't find clear instructions in their documentation on how to specify a different Django version during installation. I'd like to use Django 4.2 with cookiecutter-django since it has LTS support until 2026. How can I do this? -
How to use for loop in django email template
On my website, email is send to the admin email address when ever a user place an order. The problem I am facing, I cannot get for loop working in the email template. How can I use for loop to loop through the products ordered by the user, and display those products in the email. Below is my code email.html {% if order.cart %} <h2> Food Ordered</h2> <table style="border:1px solid black"> {% for obj in products %} <th style="border:1px solid black">Name</th> <th style="border:1px solid black">Quanity</th> <th style="border:1px solid black"> Amount</th> <tr> <td style="border:1px solid black"> {{obj.food.name}} </td> <td style="border:1px solid black"> {{obj.quantity}} </td> <td style="border:1px solid black">{{obj.amount}}</td> </tr> {% endfor %} {% endif %} I want to be able to loop products in the email template def reservationEmail(order): context={ 'order':order.cart, 'products':order.cart.foods.all(), 'name':order.name, 'number':order.number, 'date':order.datetime , 'seats':order.seats, 'OrderId':order.orderid, 'total':order.sumamount, 'quantity':order.reserved.count() } template = get_template('home/reservationnotification.html') mail_subject='Reservation/catering made' content = template.render(context) to_email='narlianafricanboucareau@gmail.com' email=EmailMultiAlternatives(mail_subject,content,to=[to_email]) email.attach_alternative(content, "text/html") email.send() -
python telegram bot async not working simultaneously in 2 groups
I have a telegram bot written with python telegram bot package with the latest release and i have a problem, the bot runs fine everything works but when i try to run it in 2** different groups** at the same time, the bot first finishes the first request in group A then process the request from group B this is a example code async def start_blackjack(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: if not await check_player(update, context): return chat_id = update.message.chat_id game = await sync_to_async(lambda: Game.objects.filter(chat_id=chat_id).order_by('-id').first())() if not game or game.ended: game, created = await sync_to_async(Game.objects.get_or_create)(chat_id=chat_id, ended=False) game.betting = True game.started = False await sync_to_async(game.save)() await asyncio.sleep(2) # Non-blocking sleep await context.bot.send_message(chat_id=chat_id, text="🃏 Set the bet amount for the blackjack game to start.") await create_poll(update, context) # Assume this is an async function await asyncio.sleep(2) # Non-blocking sleep await context.bot.send_message(chat_id=chat_id, text="🃏 Betting process has started!") return if game.betting: await update.message.reply_text("A Blackjack game is in betting progress. Wait for the betting process to end and use /join to join the game.") elif game.started: await update.message.reply_text("A game has already started. Use the /next command to be prompted when the next game starts.") elif game.join_time: await update.message.reply_text("A game is in join time. Use the … -
Heroku changing base_dir to 'app' in Django & React app
I have a django/react app with the file structure funcon(main directory // django project - contains manage.py) -funcon (sub directory // django) -core (sub directory // django) -funcon-frontend (subdir // react) When I run the project locally, everything works great. The react project is the first thing I see when I go to localhost:8000, and the auth requests work between it and the api. When I deploy to heroku, for some reason it seems like it converts my BASE_DIR to app/funcon-frontend and I can't find why it's doing that or how to change it. I am just trying to deploy the react + django app together. I use whitenoise (in my requirements.txt) settings.py BASE_DIR = Path(__file__).resolve().parent.parent dotenv_path = os.path.join(BASE_DIR, '.env') load_dotenv(dotenv_path) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'funcon-frontend', 'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [] frontend_static = os.path.join(BASE_DIR, 'funcon-frontend', 'build', 'static') if os.path.exists(frontend_static): STATICFILES_DIRS.append(frontend_static) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' WHITENOISE_ROOT = os.path.join(BASE_DIR, 'funcon-frontend', 'build') django_heroku.settings(locals(), staticfiles=False) I have a package.json at my root directory, otherwise heroku doesn't recognize the Nodejs app and it goes "name": "funcon", "version": "1.0.0", "scripts": { "heroku-postbuild": "echo … -
I can not enter the data through DRF API for model Band_qilish even it is empty
I have validation error when attempting to enter the data for the model Band_qilish through DRF API even it is empty. Help me with how to solve this problem. You can try it here: https://github.com/Diamondman51/AVIA.git Just enter some data for models Chipta and Yolovchi after that try entering data through API for the model Band_qilish passing for it existing "ismi" field from model Yolovchi and existing "raqam" field from model Chipta. It must raise exception about existing "raqam" even there is no data in Band_qilish model. I tried everything but it worked only when I removed the parameter unique from the model Chipta from field raqam. But the field raqam in this case must be unique. -
connection to server at "db" (host), post 5432 failed: FATAL: database "<db_name>" does not exist
version: '3.7' services: db: image: postgres:13 restart: always environment: POSTGRES_DB: <db_name> POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres ports: - "5432:5432" networks: - internal_network volumes: - postgres_data:/var/lib/postgresql/data backend: image: backend-image volumes: - static_volume:/src/backend/static - media_volume:/src/backend/media env_file: - ./backend/.env build: ./backend ports: - "8000:8000" depends_on: - redis - db networks: - internal_network volumes: static_volume: media_volume: postgres_data: networks: internal_network: driver: bridge I have a problem after some time I delete the database about 3 days after I do docker-compose up -d The docker-compose.yml itself is written correctly but I don't understand why the database is deleted. In the logs I looked at logs:2024-09-11 08:43:23.829 UTC [11436] FATAL: password authentication failed for user "postgres"2024-09-11 08:43:23.829 UTC [11436] DETAIL: Password does not match for user "postgres". Connection matched pg_hba.conf line 99: "host all all all md5"2024-09-11 08:44:24.551 UTC [11437] FATAL: canceling authentication due to timeout2024-09-11 08:55:20.062 UTC [11486] FATAL: database "<db_name>" does not exist