Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I maintain connection between Docker containers while having one of them connected to host machine?
I am currently deploying an application with Docker (version 27.2.1), using docker compose on debian 11. My docker-compose.yml file consists in defining 4 containers (app, api, db and ngninx). app and api are Django applications. db is a postgresql service. The whole is deployed on a machine that hosts an SMTP service on port 25. My Django app app needs to use this service to send emails to the users, but it also has to be able to connect with the other containers. For example, db is the host of the postgresql server that contains all the data managed by the Django models defined in app. I cannot find how my containers can be on the same network while having the app service in relation to the host machine. This prevents me from using the SMTP I need to use. From what I have read on this site and in the docs, it seems that it is not possible to have a service running on both network_mode=host and on a default bridge network. Here is the docker-compose.yml file. services: app: build: ./app depends_on: db: condition: service_healthy ports: - "8080:8080" volumes: ... extra_hosts: - "host.docker.internal:host-gateway" api: build: ./api depends_on: db: condition: … -
Meta Facebook Embedded Signup in Django Python
I work on a company that works with whatsapp chatbot. I created a page to make our clients signin with their facebook's business account to get permissions to send message on behalf of them. I'm implementing the embedded signup in a simple page just to get the access token. For test purposes, I created a simple backend in python to return the access token to the page. These are the codes I have: (I just replaced the ids with xxx,yyy and zzz because I think these are not needed here) Frontend <html> <head> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> window.fbAsyncInit = function () { // JavaScript SDK configuration and setup FB.init({ appId: "xxx", // Facebook App ID cookie: true, // enable cookies xfbml: true, // parse social plugins on this page version: "v20.0", //Graph API version }); }; // Load the JavaScript SDK asynchronously (function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); })(document, "script", "facebook-jssdk"); // Facebook Login with JavaScript SDK function launchWhatsAppSignup() { // Launch Facebook login FB.login( function (response) { if (response.authResponse) { console.log("response", response); const code = response.authResponse.code; // Make a call to the … -
Can I have two Libraries within one Azure Repo and install them using requirements.txt
I have a Repo with two libraries committed. Basically two folder containing different libraries within one single repo. And I want this libraries to be installed using requirements.txt. Is this possible? django-auth-adfs @ git+https://{username}:{PAT}@dev.azure.com/{organization}/{project}/_git/{repository}/django-auth-adfs@main#egg=django-auth-adfs django @ git+https://{username}:{PAT}@dev.azure.com/{organization}/{project}/_git/{repository}/django@main#egg=django I found this command to put within requirements.txt but this throws errors while installing. -
How to filter Longitude/Latitude on Django PointField directly?
I want to filter directly on a lat/lng value on a GeoDjango PointField. e.g. geolocation__lat__lte=40.0 Typically in django i can access Latitude/Longitude directly like geolocation.x or geolocation.y so i tried to filter like geolocation_y__lte=40.0. FieldError: Unsupported lookup 'y' for PointField or join on the field not permitted. was the result. ChatGPT wasn't able to help out and I don't find a related question here on stackoverflow. Will be thankful for any help. -
How do I deploy my containerized Nextjs and Django app to render?
I successfully containerized my Django and Nextjs apps with docker, these containers are running locally, but deploying to Render a hosting platform, I have an issue binding my service to a port, at least that's the log error message I am getting, Port scan timeout reached, no open ports detected. Bind your service to at least one port. If you don't need to receive traffic on any port, create a background worker instead. Error Log docker-compose.yaml version: "3.9" services: postgis: image: geonode/postgis:15.3 container_name: postgis4agro_watcher volumes: - ./init-db:/docker-entrypoint-initdb.d/ - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASSWORD=${DB_PASSWORD} ports: - "5432:5432" restart: always networks: - agrowatcher-api nginx: build: context: ./nginx dockerfile: Dockerfile container_name: nginx4agro_watcher restart: always depends_on: - awatcher-frontend ports: - 8080:8080 networks: - agrowatcher-api django: build: context: . dockerfile: Dockerfile container_name: django4agro_watcher env_file: - .env command: python manage.py runserver 0.0.0.0:8000 volumes: - ./:/home/geouser/agrowatcher ports: - "8000:8000" restart: always depends_on: - postgis networks: - agrowatcher-api awatcher-frontend: build: context: ./awatcher-frontend dockerfile: Dockerfile container_name: awatcherfrontend4agro_watcher volumes: - ./awatcher-frontend:/usr/src/app - /usr/src/app/node_modules ports: - "3000:3000" environment: - NODE_ENV=development # stdin_open: true # tty: true depends_on: - django networks: - agrowatcher-api networks: agrowatcher-api: driver: bridge volumes: postgres_data: I created a shell script to use the … -
Problem installing libpq in Docker for Django project
I'm trying to setup my Django project with docker and use postgres for db, and for that I need to install libpq: RUN apk update --no-cache && apk add --no-cache libpq But I got this error during run docker compose up --build: => ERROR [backend builder 3/7] RUN apk update --no-cache && apk add --no-cache postgresql-dev gcc python3-dev musl-dev nano 10.6s => ERROR [backend stage-1 6/14] RUN apk update --no-cache && apk add --no-cache libpq dcron 10.6s ------ > [backend builder 3/7] RUN apk update --no-cache && apk add --no-cache postgresql-dev gcc python3-dev musl-dev nano: 0.559 fetch https://dl-cdn.alpinelinux.org/alpine/v3.20/main/x86_64/APKINDEX.tar.gz 5.560 WARNING: fetching https://dl-cdn.alpinelinux.org/alpine/v3.20/main: temporary error (try again later) 5.560 fetch https://dl-cdn.alpinelinux.org/alpine/v3.20/community/x86_64/APKINDEX.tar.gz 10.57 WARNING: fetching https://dl-cdn.alpinelinux.org/alpine/v3.20/community: temporary error (try again later) 10.57 4 unavailable, 0 stale; 37 distinct packages available ------ ------ > [backend stage-1 6/14] RUN apk update --no-cache && apk add --no-cache libpq dcron: 0.555 fetch https://dl-cdn.alpinelinux.org/alpine/v3.20/main/x86_64/APKINDEX.tar.gz 5.560 fetch https://dl-cdn.alpinelinux.org/alpine/v3.20/community/x86_64/APKINDEX.tar.gz 5.560 WARNING: fetching https://dl-cdn.alpinelinux.org/alpine/v3.20/main: temporary error (try again later) 10.57 WARNING: fetching https://dl-cdn.alpinelinux.org/alpine/v3.20/community: temporary error (try again later) 10.57 4 unavailable, 0 stale; 37 distinct packages available ------ failed to solve: process "/bin/sh -c apk update --no-cache && apk add --no-cache libpq dcron" did not complete successfully: exit code: 4 … -
Django-redis - Connection Closed errors after timeout set to 0
I am using Nautobot (Django-based application) that utilises Redis and Celery for asynchronous task execution. Randomly, when accessing the jobs page, I get the below error stating the Redis server connection was closed. Originally, I had Redis running in a container and later migrated to Google MemoryStore as part of the troubleshooting. Both platforms have the same issue. I've tried updating the redis configuration on both to disable timeouts: timeout 0 As well as setting the configuration in Django but the issue continues. # CACHE Configuration CACHE_RETRY = Retry(ExponentialBackoff(), 3) CACHES = { "default": { "BACKEND": "django_prometheus.cache.backends.redis.RedisCache", "LOCATION": f"{os.getenv('CACHE_BROKER_URL', 'redis://127.0.0.1:6379')}/0", "TIMEOUT": 300, "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "PASSWORD": f"{os.getenv('CACHE_AUTH_STRING', '')}", "SOCKET_CONNECT_TIMEOUT": 10, "SOCKET_TIMEOUT": 0, "CONNECTION_POOL_KWARGS": { "ssl_cert_reqs": os.getenv('CACHE_CERT_REQUIRED', 'None'), "retry": CACHE_RETRY, "retry_on_timeout": True } }, } } CONTENT_TYPE_CACHE_TIMEOUT = int(os.getenv("CACHE_CONTENT_TYPE_TIMEOUT", "0")) REDIS_LOCK_TIMEOUT = int(os.getenv("CACHE_LOCK_TIMEOUT", "0")) CELERY_BROKER_URL = os.getenv("CACHE_BROKER_URL", "redis://127.0.0.1:6379") CELERY_TASK_SOFT_TIME_LIMIT = int(os.getenv("CACHE_TASK_SOFT_TIME_LIMIT", str(5 * 60))) CELERY_TASK_TIME_LIMIT = int(os.getenv("CACHE_TASK_TIME_LIMIT", str(10 * 60))) CELERY_BROKER_TRANSPORT_OPTIONS = { "ssl": { "ssl_cert_reqs": os.getenv('CACHE_CERT_REQUIRED', 'None') } } CELERY_RESULT_BACKEND_TRANSPORT_OPTIONS = { "ssl": { "ssl_cert_reqs": os.getenv('CACHE_CERT_REQUIRED', 'None') } } if os.getenv('CACHE_CERT_REQUIRED', 'None') == 'required': CACHES['default']['OPTIONS']['CONNECTION_POOL_KWARGS']['ssl_ca_certs'] = os.getenv('CACHE_CERT_LOCATION', '') CELERY_BROKER_TRANSPORT_OPTIONS['ssl']['ssl_ca_certs'] = os.getenv('CACHE_CERT_LOCATION', '') CELERY_RESULT_BACKEND_TRANSPORT_OPTIONS['ssl']['ssl_ca_certs'] = os.getenv('CACHE_CERT_LOCATION', '') # Construct the new URL for Celery schema, host = os.getenv("CACHE_BROKER_URL", "redis://127.0.0.1:6379").split('://') CELERY_BROKER_URL … -
Django's makemessages generates corrupt po file
My code contains this line (beside lots more i18n texts): filter_text = _('Filter') I generate the "de" locale po file (see missing prefix "#:"): django-admin makemessages --locale de -i venv The resulting po file ist corrupt: #: .\oam\views\article\article_list.py:138 #: .\oam\views\fillup\fillup_list.py:109 #: .\oam\views\setting\setting_list.py:49 .\oam\views\stock\stock_list.py:75 #: .\oam\views\tom_article\tom_article_list.py:53 #: .\oam\views\transaction\transaction_list.py:90 msgid "Filter" msgstr "Filter" Running makemessages again of course leads into errors: CommandError: errors happened while running msgmerge c:\work\pro\ceratizit\apollo\oam\locale\de\LC_MESSAGES\django.po:1915:3: syntax error c:\work\pro\ceratizit\apollo\oam\locale\de\LC_MESSAGES\django.po:1915: keyword "oam" unknown c:\work\pro\ceratizit\apollo\oam\locale\de\LC_MESSAGES\django.po:1915: keyword "views" unknown c:\work\pro\ceratizit\apollo\oam\locale\de\LC_MESSAGES\django.po:1915: keyword "stock" unknown c:\work\pro\ceratizit\apollo\oam\locale\de\LC_MESSAGES\django.po:1915: keyword "stock_list" unknown c:\work\pro\ceratizit\apollo\oam\locale\de\LC_MESSAGES\django.po:1915: keyword "py" unknown msgmerge: found 6 fatal errors When removing the i18n at this line the makemessages works well: filter_text = 'Filter' I'm totally lost. Any hints? Thanks! -
Button to download file and redirect to new page
How do I enable my button to download and redirect to a new page? I have tried many code combination but it just downloads and does not redirect <div class="banner"> <h3>Download your file:<br> {{ filename }}</h3> <div> {% csrf_token %} <form action="{% url 'download_pdf' %}" enctype="multipart/form-data" method="post"> {% csrf_token %} <button onclick="openTab()" class="btn btn-primary w-20" id="myBtn" tabindex="4">Download PDF </button> </form> </div> </div> <script> function openTab() { window.open('home'); } </script> -
How to add fields to serializer
I would like to add foreign key fields to DRF serializer. I need API endpoint with information of Publication details with all Comments to this publication with all Images to this publication and with Likes number to this publication. Models class Publication(models.Model): pub_text = models.TextField(null=True, blank=True) pub_date = models.DateTimeField(auto_now_add=True) pub_author = models.ForeignKey(User, on_delete=models.CASCADE) class Comment(models.Model): com_text = models.TextField(null=True, blank=True) com_like = models.BooleanField(default=False) com_author = models.ForeignKey(User, on_delete=models.CASCADE) com_to_pub = models.ForeignKey(Publication, on_delete=models.CASCADE, related_name='comment_author') com_date = models.DateTimeField(auto_now_add=True, null=True) class Image(models.Model): image = models.ImageField(upload_to='images', null=True) image_to_pub = models.ForeignKey(Publication, on_delete=models.CASCADE, null=True, related_name='images') Serializers class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ['image'] class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ['com_text', 'com_like', 'com_date', 'com_author'] class PublicationSerializer(serializers.ModelSerializer): class Meta: model = Publication fields = ['id', 'pub_text', 'pub_author', 'pub_date'] def to_representation(self, instance): representation = super().to_representation(instance) representation['comment'] = CommentSerializer(instance.comment_author.all(), many=True).data representation['image'] = ImageSerializer(instance.images.all(), many=True).data return representation Views class PublicationViewSet(viewsets.ModelViewSet): queryset = Publication.objects.all() serializer_class = PublicationSerializer class ImageViewSet(viewsets.ModelViewSet): queryset = Image.objects.all() serializer_class = ImageSerializer class CommentViewSet(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer By my logik Like to Publication can be given by Comment author if comment was created. I used <to_represtntation> method to add fields to Publication serializer. It works as i would need but not sure … -
How does PostgreSQL handle get() in Django for exact file path matches and its performance?
I’m using Django with a PostgreSQL database, and I have a model that stores file paths (specifically S3 file paths) in a CharField, like this: class File(models.Model): file_path = models.CharField(max_length=255) I often retrieve a single file record using Django’s get() method with an exact S3 file path match: file = File.objects.get(file_path='/bucket/path/to/file.txt') This translates to the following SQL query: SELECT * FROM my_table WHERE file_path = '/bucket/path/to/file.txt' LIMIT 1; I want to understand what happens under the hood when PostgreSQL processes this query. Specifically: 1. How does PostgreSQL handle the comparison of strings when using the = operator on a CharField with an S3 file path? 2. Does PostgreSQL behave differently if there’s an index on the file_path column, and how does it decide between using an index or performing a sequential scan? 3. Is it beneficial to create an index on the file_path field for better performance, -
Creating Forms that Redirects to Different URL When Successful
So I have created two folders (Aside from my main project folder) One of my folders is the main app and the second folder is a users folder. Error Message: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/users/register Using the URLconf defined in cooknook.urls, Django tried these URL patterns, in this order: admin/ users/ register/ [name='cooknook-register'] [name='cooknook-home'] about/ [name='cooknook-about'] account/ [name='cooknook-account'] The current path, users/register, didn’t match any of these. ^^ Error Thrown So In my views.py inside of my users folder I am telling it after success: ` def register(response): if response.method == "POST": form = UserCreationForm() if form.is_valid(): form.save()` return redirect('cooknook-home') Basically, I did already try to outsource the problem and tried to implement 'reverse' function in this which did not seem to work at all. The problem is that it seems it is trying to find the urls/html(temps) inside of my cooknookapp folder which is my main app folder. I'm needing it to redirect to home.html (located inside of my main app folder) How can I get Django to look outside of the Users/ Dir for this? I was expecting for it to send me to the home page which is located in the cooknookapp … -
How to expose the drf_spectacular autogenerated documentation of a class-based view that has no direct reference in urls.py?
I have a Django app that based on specific condition, executes one or another class-based view. def compatibility_whatever_view(request: Request, *args, **kwargs) -> Response: if is_legacy: return LegacyWhateverView.as_view()(request, *args, **kwargs) else: return WhateverView.as_view()(request, *args, **kwargs) I have my WhateverView and LegacyWhateverView with fully compatible API. urlpatterns = [ path( "whatever/<uuid:whatever_id>/", compatibility_whatever_view, name="whatever_list_whatevers", ), ] I want to expose the documentation of WhateverView using drf_spectacular. Unfortunately I am failing to do so, as it seems the swagger.yml file is generated only if the class-based view is directly exposed in the urlpatterns, otherwise it does not know how to build the URL endpoint. This totally makes sense, but I would like to be able to somehow expose the automatically generated of WhateverView to the public. I have tried a bit of magic using: @drf_spectacular.utils.extend_schema(operation_id="whatever_list_whatevers") @rest_framework.decorators.api_view() def compatibility_whatever_view(request, *args, **kwargs): ... but the generated documentation was lacking the details that are otherwise present when I directly reference the class-based view. -
django CMS vs Django
We're planning to build a application tracking system with multiple role and permission. My question is : Which is the best platform django CMS or Django ? I am in the impression that Django CMS comes with all the role / Groups / Permission stuff as default, but in Django I see we have groups I don't see permission concept. Share your expert advices. -
How to mocking a function that returns some value
For example, there is a view that processes a user registration request. The view accepts a phone number and sends an SMS with a code to it. The code is generated by an additional function. Here's how to mocking this function to send the code I need? This is my view def post(self, request): serializer = ReviewerSignUpSerializer(data=request.data) serializer.is_valid(raise_exception=True) phone = serializer.validated_data.get("phone") confirmation_code = get_confirmation_code() cache.set( key=str(phone), value=confirmation_code, timeout=settings.CONFIRMATION_CODE_LIFETIME ) send_sms_task.apply_async([confirmation_code, str(phone)]) This is a function that generates a confirmation code def get_confirmation_code() -> str: seq = list(map(lambda x: str(x), range(10))) shuffle(seq) code = choices(seq, k=settings.INVITE_CODE_LENGTH) return "".join(code) Test function def test_saving_confirmation_code_in_cache(self, client, cache): phone = "+79389999999" generated_code = "9999" with patch("api.v1.authentication.utils.get_confirmation_code", return_value=generated_code): client.post(reverse('api:v1:signup'), data={'phone': phone}) confirmation_code = cache.get(str(phone)) assert confirmation_code is not None assert confirmation_code == generated_code -
Wagtail django.db.utils.OperationalError: (1463, "Non-grouping field 'numchild' is used in HAVING clause")
I'm working on a Django project and I've encountered an issue that I'm unable to resolve. When I try to run my application, I get the following error: django.db.utils.OperationalError: (1463, "Non-grouping field 'numchild' is used in HAVING clause") I'm not sure what's causing this error. I'm not explicitly using a HAVING clause in my queries, and 'numchild' is a field that's managed by Django's** Wagtail** module, not something I've added myself. I'm using the following packages: wagtail>=5.0 mysqlclient==2.2.4 Every things working fine locally using sqlite. I tried to downgrade my mysqlclient version from 2.2.4 to 2. Without sucess. I would like to have the result as sqlite. -
Redis Lock with Django unexpected behaviour
I am running redis:7.2.4 in a docker container. In Djano settings.py redis is set up like this: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://redis:6379', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', }, }} This is the implementation of a context manager for a locking (I just added thread_local=False without effect): from django.core.cache import cache LOCK_CLEANUP_TIMEOUT_SEC = 20 LOCK_AQUIRE_WAIT_TIMEOUT_SEC = 2 class RedisLock: def __init__(self, lock_id, timeout=LOCK_CLEANUP_TIMEOUT_SEC): self.lock_id = lock_id self.timeout = timeout def __enter__(self, aquire_timeout = LOCK_AQUIRE_WAIT_TIMEOUT_SEC): self.aquired = cache.lock(self.lock_id, blocking_timeout=aquire_timeout, thread_local=False) return self.aquired def __exit__(self, exc_type, exc_value, traceback): if self.aquired: cache.delete(self.lock_id) Consider the output of the django shell: >>> lock_name = 'test123' >>> with RedisLock(lock_name) as acquired1: ... if acquired1: ... print("1 acquired", acquired1) ... with RedisLock(lock_name) as acquired2: ... if not acquired2: ... print("2 not acquired (expected behavior)", acquired2) ... else: ... print("2 acquired (this should not happen)", acquired2) ... else: ... print("1 not acquired", acquired1) ... 1 acquired <redis.lock.Lock object at 0x0000023B4190BC10> 2 acquired (this should not happen) <redis.lock.Lock object at 0x0000023B4190BDF0> Does somebody have an idea why this happens? The second lock must not be acquired before leaving the context manager of the first lock. -
when i try to use "django-admin runserver" on a project that worked about a month ago (i didnt edit anything btw) this happened (on VSCode)
PS F:\filenaem\djangler> django-admin runserver Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "C:\Users\user\AppData\Local\Programs\Python\Python312\Scripts\django-admin.exe\__main__.py", line 7, in <module> File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\commands\runserver.py", line 75, in execute super().execute(*args, **options) File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 459, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\commands\runserver.py", line 82, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: ^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\conf\__init__.py", line 81, in __getattr__ self._setup(name) File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\conf\__init__.py", line 61, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. tried to use the django-admin runserver command and expected it to work, because its a finished project that i made with the assistance of my old teacher, but for whatever reason when i try to run it now 2 months later and after moving it to another computer via an external disk it doesnt work, any help? also "python manage.py runserver" doesnt work eighter, it just gives me this: PS F:\filenaem\djangler> python manage.py runserver C:\Users\user\AppData\Local\Programs\Python\Python312\python.exe: can't open file 'F:\\filenaem\\djangler\\manage.py': … -
Django Tenant throwing raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) error
I am working on a Django project that uses Django Channels, Daphne, and Django Tenants for multitenancy and WebSocket communication. My project structure includes a project folder and several application folders. In the project folder, I have the usual files like asgi.py, wsgi.py, settings.py, and consumers.py (for handling Django Channels). I am not using routing.py. In the application folder, I have files like models.py, serializers.py, views.py, and urls.py. The WebSocket communication works fine, but I encounter an issue when trying to import a service module in consumers.py. asgi.py import os from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.urls import path, re_path from .consumers import ABConsumer os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'autobiz.settings') import django django.setup() # Initialize Django ASGI application early to ensure the AppRegistry # is populated before importing code that may import ORM models. django_asgi_app = get_asgi_application() application = ProtocolTypeRouter({ "http": django_asgi_app, # Just HTTP for now. (We can add other protocols later.). "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ #path("ws/admin/", ABConsumer.as_asgi()), re_path(r'ws/server/(?P<tenant_name>\w+)/$', ABConsumer.as_asgi()), ]) ) ), }) consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json import logging **from autobiz.abshared.services import process_token ** # Setting up logging logger = logging.getLogger(__name__) class ABConsumer(AsyncWebsocketConsumer): async def connect(self): # … -
CashApp Payment Method Not Rendering in Django with Adyen Integration
I'm trying to integrate Adyen's payment methods (including CashApp) into my Django web application, but the CashApp payment method isn't rendering on the front end. Instead, I receive the following error: ERROR Error during initialization ERROR: Error during initialization at e.<anonymous> (https://checkoutshopper-test.adyen.com/checkoutshopper/sdk/5.68.0/adyen.js:1:460538) at P (https://checkoutshopper-test.adyen.com/checkoutshopper/sdk/5.68.0/adyen.js:1:41524) at Generator.<anonymous> (https://checkoutshopper-test.adyen.com/checkoutshopper/sdk/5.68.0/adyen.js:1:42844) This same code is rendering the card payment gateway but not working on the cashapp. My html Code: Where is used adyen sdk=5.68.0 version. Version greater than 5.69.0 gives different error that AdyenCheckout is not defined I don't know how to solve that too. <link rel="stylesheet" href="https://checkoutshopper-test.adyen.com/checkoutshopper/sdk/5.68.0/adyen.css"> <div id="component"></div> <script src="https://checkoutshopper-test.adyen.com/checkoutshopper/sdk/5.68.0/adyen.js"></script> async function startCheckout() { const checkoutSessionResponse = await callServer({% url 'sessions' %}); const checkout = await createAdyenCheckout(checkoutSessionResponse); checkout.create(type).mount("#component"); } async function createAdyenCheckout(session) { return new AdyenCheckout({ clientKey, session: session, paymentMethodsConfiguration: { cashapp: { amount: { value: 100, currency: "USD" }, countryCode: "US" } } }); } django view.py file: def adyen_sessions(request): # payments = ["card", "cashapp", "ideal"] session_response = { 'client_key': settings.ADYEN_CLIENT_KEY, 'method': 'cashapp' } return render(request, 'component.html', context=session_response) def sessions(request): if request.method == "POST": adyen = Adyen.Adyen() adyen.payment.client.xapikey = settings.ADYEN_API_KEY adyen.payment.client.platform = settings.ADYEN_ENVIRONMENT adyen.payment.client.merchant_account = settings.ADYEN_MERCHANT_ACCOUNT request_data = { 'amount': { "value": 100, # amount in minor units "currency": "USD" … -
Oauth2 doesn't redirect to my flutter application after successful login
I am trying to implement oauth2 with flutter_appauth package. After successful login the web page should redirect to my mobile application. At this moment, it just stays in web (redirecting to web home page). I'm currently getting this error Redirect to scheme 'com.app.app` is not permitted. Here is the code oauth2.dart Future<void> login() async { try { final AuthorizationTokenResponse result = await appAuth.authorizeAndExchangeCode( AuthorizationTokenRequest( 'client_id', 'com.app.app:/oauthredirect', // discoveryUrl: // "http://10.0.2.2:8000/api/oauth2/.well-known/openid-configuration", serviceConfiguration: const AuthorizationServiceConfiguration( authorizationEndpoint: 'http://10.0.2.2:8000/api/oauth2/authorize', tokenEndpoint: 'http://10.0.2.2:8000/api/oauth2/token', ), scopes: ['openid', 'profile', 'email'], ), ); print("Received Token!"); // Successfully received the token print(result); } catch (e) { print('Login error: $e'); } } build.gradle defaultConfig { applicationId "com.app.app" minSdkVersion 26 targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName multiDexEnabled true manifestPlaceholders += [appAuthRedirectScheme: 'com.app.app'] } Note: login() function invoked when user clicks the login button on the login screen. Also, I've tried implementing oauth2 with discoveryUrl and it just crashes the app immediately after login() function is called. Last thing I want to mention is I have already checked redirection uri in admin panel and it's correct. Oauth2 was implemented with Django oauth2 toolkit. -
Django SVG not loading on Front-End
Images are located in: root folder -> static -> admin -> img -> logo.svg {% load static %} <a class="navbar-brand" href="/"> <img src="{% static 'admin/img/logo.svg' %}" alt="Logo"> </a> But I am getting this error: "GET /static/admin/img/devoro-logo.svg HTTP/1.1" 404 Hello, I am having an issue with my Django project, I am trying to call my newly added .svg to my base.html like so. All of the old images works perfectly, but the issue seems to lie with the newly added ones. The settings.py is configured correctly and everything seems to be correct, but for some reason I am getting this error. -
Closing Socket Reverts Database Data to Earlier State
I'm building a Django SPA, which uses HTTPS requests as well as Django Channels (Socket Communication) for real time updates. When a user logs in, the socket creates an instance(?) for that user, of which data matches the user data in the database. If you change the user data in the database (for example increment wins or change username), this data is not automatically carried over to the socket session, so I will have 2 different states representing the same user. When I then interrupt the socket instance, the database reverts back to the state it was in before the changes. I won't post code, I'm just curious about the description of this anomaly Do I have to refresh manually the user's state in the socket after each database change related to the user? Or is there some way around it? **What I've tried ** When I'm saving the new data to the websocket and also update it's in-memory data e.g: self.scope["user"].username = new_username self.user.username = username That seems to work. However I'm curious if that is necessary for every user related update, or if there is a shorcut to this problem. -
Django SMTPAuthenticationError when using the same variable name for EMAIL_HOST_PASSWORD in .env and settings.py
I am working on a Django project where I use Gmail for email services. I have the following configuration in my .env file: EMAIL_HOST_USER=gmail@gmail.com EMAIL_HOST_PASSWORD=password And in my settings.py, I load these variables as follows: EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD') When I try to send an email through my application, I encounter an SMTPAuthenticationError. However, when I change the name of the variable in the .env file, it works fine, but the password is no longer masked. How can I fix this while keeping the password masked? -
Django random post not showing on base.html
I'm trying to get ads to show on the sidebar of my website (in base.html). However the ad isn't displaying. The code I'm using is: views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * import random def base(request): allSideAds=SideBarAd.objects.all() random_sideAd = random.choice(allSideAds) if allSideAds else None return render(request, 'base.html', {'random_sideAd': random_sideAd}) models.py from django.contrib import admin from django.db import models from django.urls import reverse class SideBarAd(models.Model): AdImage = models.ImageField(help_text='Enter Image Here') AdLink = models.URLField() MaxAdViews = models.PositiveBigIntegerField() AdViews = models.PositiveBigIntegerField() Approved = models.BooleanField() def get_absolute_url(self): return self.AdImage base.html {% if random_sideAd %} <a href="{{ random_sideAd.AdLink }}"> <img src="{{ random_sideAd.AdImage.url }}" alt="Ad Image"> </a> {% endif %} When I load a page, the ad that's in my database isn't shown through base.html.