Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I add 30-minute intervals to the django-grapelli TimeField?
I would like to add 30-minute time intervals instead of the default 1-hour intervals as seen from the screenshot below: screenshot I have tried asking ChatGPT, but the answers were unhelpful. Thank-you in advance. -
Get all Properties along with their allowed_tenants in a single query. Django and React
I have two models Property and Tenants. Each Property can have multiple allowed_tenants. Models I want a query where it fetches all properties along with their allowed_tenants in a single query(possibly less number of queries) using django orm class Tenants(models.Model): tenant_type = models.CharField(verbose_name='tenant type', max_length=32) def __str__(self): return self.tenant_type class Property(models.Model): owner = models.ForeignKey('user.User', on_delete=models.CASCADE, related_name='properties') property_name = models.CharField(verbose_name='property name', max_length=64) category = models.CharField(verbose_name='category', choices=Choices.category_choices, max_length=16) bathrooms = models.IntegerField(verbose_name='bathrooms', default=1) region = models.ForeignKey(Area, unique=True, related_name='properties', on_delete=models.CASCADE) # area = models.CharField(verbose_name='area', max_length=128) landmark = models.CharField(verbose_name='landmark', max_length=32) expected_rent = models.CharField(verbose_name='expected rent', default='not disclosed', max_length=16) expected_deposit = models.CharField(verbose_name='expected deposit', default='not disclosed', max_length=16) available_from = models.DateField(verbose_name='available from', default=datetime.date.today) allowed_tenants = models.ManyToManyField(Tenants, related_name='properties') likes = models.IntegerField(verbose_name='like', default=0) last_updated = models.DateField(verbose_name='last updated', auto_now_add=True) The result i am expecting should be like => [{...property_details, tenants: ['family', 'bachelor'], property_name: 'property1'}, {...}] i tried something like this, but its giving me multiple records for a single property with different tenants in each property properties = Property.objects.filter(allowed_tenants__tenant_type__in=['family']).annotate( property_owner=F('owner__first_name'), city=F('region__city__city'), area=F('region__area_name'), tenants=F('allowed_tenants__tenant_type'), ).values( 'property_owner', 'property_name', 'category', 'bathrooms', 'city', 'area', 'landmark', 'expected_rent', 'expected_deposit', 'available_from', 'tenants', 'likes', 'last_updated' ) [{...property1, tenants: 'family', property_name:'property_1'}, {...property1, tenants: 'bachelor', property_name:'property_1'}, {...}] -
trigger an action when a specific field is changed in Django models
I needs to change the OTP_expire value whenever OTP field change it's value class Account(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=60, null=True) username = models.CharField(max_length=30, unique=True) password = models.CharField(blank=True) OTP = models.IntegerField(null=True) OTP_expire = models.DateTimeField(null=True) For that I thought of creating a trigger, but I could not figure out how to identify if the OTP field has changed or if another field has changed. -
Django with Nginx and Cloudflare: "400 Bad Request" on Redirect
I'm integrating an Iranian Stripe-like bank gateway provider with my Django application. When a user completes a successful purchase, the gateway redirects them back to our website using a predefined redirect URL to finish the deposit process. However, some users encounter a "400 Bad Request" error (as shown in the screenshot below) when they are redirected back to our site. The error message indicates that "The plain HTTP request was sent to HTTPS port. Here is my Nginx configuration: server { listen 80 default_server; server_name _; return 301 https://$server_name$request_uri; } server { listen 8443 default_server ssl http2; listen [::]:8443 ssl http2; server_name mydomain.com; ssl_certificate /etc/nginx/ssl/mydomain.com.cer; ssl_certificate_key /etc/nginx/ssl/mydomain.com.cer.key; access_log /project/logs/nginx/access.log; add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; add_header X-Frame-Options SAMEORIGIN; add_header X-XSS-Protection "1; mode=block"; add_header X-Content-Type-Options nosniff; add_header Referrer-Policy strict-origin-when-cross-origin; location / { try_files $uri @proxy_api; } location @proxy_api { proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_redirect off; proxy_pass http://web:8000; } location /static/ { autoindex on; alias /project/app/staticfiles/; } location /logs { autoindex on; alias /project/logs; types { text/plain log; } } } Screenshot: -
Terminate(Revoke) a Celery Task in Eventlet Pool
I switched prefork pool to eventlet. In my case my termination method not more working and rising this error: django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 139661231139648 and this is thread id 139661089517376. Using django-db as result backend. Termination Method: def terminate(self): """ Terminate a service with bot_code """ task_name = f"{self.bot_code}_instance" try: task = PeriodicTask.objects.get(name=task_name) task.enabled = False task.save() celery_task_id = TaskController.get_celery_task_id_by(search_field="task_name", search_value=task.task, status="STARTED") if celery_task_id: current_app.control.revoke(celery_task_id, terminate=True) return Response({'message': 'Task terminated successfully.'}, status=status.HTTP_200_OK) except PeriodicTask.DoesNotExist: return Response({'error': 'Task does not exist.'}, status=status.HTTP_404_NOT_FOUND) -
how to pre-fill an fields for authentication method on the swagger or test it interactive api using drf spectacular?
i need to pre-filled fields like username, password for authentication on drf spectacular i'm using the schema and the auth,and i need to pre fill the fields like : username:text, password:text but i didn't find any document for that: "auth": [{"Api-Key Auth": []}, {"Basic Auth": []}, {"JWT Auth": []}], i've tried to add on the auth like this, but still can see the fields empty: class KeycloakBasicAuthExtension(OpenApiAuthenticationExtension): target_class = "contrib.keycloak.auth.KeycloackBasicAuth" name = "Basic Auth" priority = 1 match_subclasses = True def get_security_definition(self, auto_schema): return { "type": "http", "scheme": "basic", "x-example": {"username": "test", "password": "test"}, } and even i've tried to add n Request Name on the schema, but i can still see the Request Name when deploy to the gitbook as None: class CheckoutSchema(ModelSchema): view_class = CheckoutCreateApiView post = { "summary": "Create a new Payment Transaction", "description": "Create a new Payment Transaction", "tags": [ "Checkout API", ], "operation_id": "create_payment_transaction_checkout", "methods": ["POST"], "request": get_checkout_serializer(name="CheckoutPOSTRequestSerializer"), "responses": { 201: get_checkout_serializer(name="CheckoutPOSTResponseSerializer"), 400: PolymorphicProxySerializer( component_name="ClientErrors", serializers=[ serializers.FieldErrorSerializer, serializers.NestedFieldErrorSerializer, serializers.GenericErrorMessage, ], resource_type_field_name=None, ), 401: serializers.GenericErrorMessage, 403: serializers.GenericErrorMessage, 404: serializers.GenericErrorMessage, 415: serializers.GenericErrorMessage, 423: serializers.GenericErrorMessage, }, "examples": [ OpenApiExample( "Create Payment Transaction Example", summary="create a new payment transaction request example", description="This example demonstrates how to send a complete … -
Django: Performing actions after an object is created or updated
I've got a model called EventMembership which determines whether someone is attending the event or not:- class EventMembership(models.Model): user = models.ForeignKey(User, related_name='eventmemberships') is_attending = models.BooleanField() I also have an EventFee model which is used to track the user's fees for events:- class EventFee(models.Model): user = models.ForeignKey(User, related_name='eventfees') amount = models.DecimalField() If a user is attending the event, they should have a fee for that event's price. If not, they should not have a fee. What is the best way for me to handle the creating, updating or deleting of these fees? I've seen a lot of people warn against using signals and I have had problems with signals in the past but they seem like the perfect solution. I suppose it's signals or override the save() method on the model, isn't it? But overriding the save() method would mean the fees get updated every time the model is saved which seems bad to me. Any other suggestions? Note: I'm using Django Rest Framework for this so these EventMemberships can be created, updated or deleted through that. But they can also be updated via a couple of other mechanisms, like a user deleting their account, for example - where all of … -
Hosting/Joining Zoom Video Sessions Across Web application in Django and Flutter SDKs
I have integrated the Zoom Video SDK in my web application using the Video Web SDK in JavaScript. I am having trouble hosting/joining a video session using the session name and passcode passed from the Flutter SDK, which is integrated for the Android platform. I am using the same Zoom Video SDK account with the same SDK key and secret, and sharing the session name between the two applications. Is it not possible to do it this way? Do I need to take care of anything else? -
Issues with Gunicorn Not Finding Modules on EC2 Instance
I have a Django application running on an EC2 instance (following this tutorial). When I start the server using python manage.py runserver, everything works fine. However, when I try to use Gunicorn to serve my application, I encounter errors indicating that many modules cannot be found. Here's what I have done so far: Installed Gunicorn and requirements in my virtual environment using. Activated my virtual environment. Verified that my wsgi.py file is correctly configured. My wsgi.py looks like this: python import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') application = get_wsgi_application() When i try to start the gunicorn I get errors like this: `ModuleNotFoundError: No module named 'myapp'` for example: `ModuleNotFoundError: No module named 'boto'` Then when i resolved that one im getting more and more Im using python 3.11 and the following libraries: django==3.2.10 setuptools<58.0.0 six==1.16.0 django-environ==0.4.0 whitenoise==3.2.2 django-braces==1.10.0 django-crispy-forms==1.11.0 django-model-utils==2.6 Pillow<10 # was 3.4.2 before Catlina update django-allauth==0.61.1 awesome-slugify==1.6.5 pytz==2019.3 django-redis==4.5.0 redis>=2.10.5 selenium==3.6.0 django-filter==23.5 django-widget-tweaks==1.4.1 dateparser==0.7.0 paramiko==2.4.0 django-background-tasks==1.2.5 PyPDF2==1.26.0 python-docx==1.1.0 docxtpl==0.16.7 mock==2.0.0 twocaptchaapi==0.3 XlsxWriter==1.2.7 reportlab==4.0.0 openpyxl==2.6.4 django_tables2==2.7.0 pymysql==1.1.0 django-elasticsearch-dsl==8.0 coverage==4.2 django-coverage-plugin==1.3.1 Sphinx==1.4.8 django-extensions==3.2.3 Werkzeug==0.11.11 django-test-plus==1.0.16 factory_boy==2.7.0 django-debug-toolbar==1.6 ipdb==0.13.13 pytest-django==3.0.0 pytest-sugar==0.7.1 requests_aws4auth==0.9 gunicorn==21.2.0 #must be in requirements.txt Dont really know why runserver works fine but not with gunicorn. Has … -
UpdateView in django
i can update email and others using the generic edit view "UpdateView" by giving the attribute name of my html inputs the corresponding field name so name="email" and so on. But the same thing doesn't work with field "user_permissions" model = User fields = [ "email", "is_superuser", "is_active", "is_staff", "user_permissions", ] // options are added with a js event handler -
What Price Plan of Heroku should I buy for hosting my Django App?
I have made my web-based app using Django Framework, and it's all done. Now I want to upload it using Heroku, but we should buy heroku plan to start use it, so What is the best price plan to host it (based on actual Heroku Pricing Plan 2024)? I have seen all the Price plan but a little bit confusing for me to choose which one is the best price plan for my web-app -
Django One UpdateView for different models
There are several models in my Django project with one similar field - "comment". I want to create an UpdateView for updating only this one field. I can do it by writing an UpdateView for each model. But I am wondering if can I write one UpdateView class for each of these models if the functionality of the class is the same, the model name needs to be only changed. -
Django middleware can record request log, but django async view somethings was not executed
request will be recorded by the middleware and executed in async view, but in some cases, it will not be executed in view. Settings: Python: 3.10.12 Django: 4.2.1 middleware settings: MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ... "utils.middleware.RequestMiddleware", ] RequestMiddleware: class RequestMiddleware(MiddlewareMixin): def process_view(self, request, view_func, view_args, view_kwargs): req_str = "reqeust user:{} request method:{} request path:{} request body:{}".format( request.user, request.META["REQUEST_METHOD"], request.path, request.body ) logger.info(req_str) return None def process_response(self, request, response): data = response.content data = data.decode("utf-8") logger.info("response status code:{} data:{}".format(response.status_code, data)) return response def process_exception(self, request, exception): logger.error(traceback.format_exc()) views.py: async def report(request): my_views.delay() # celery task return send_message({"result": 0}) -
Django: Upload File to Firebase and Save File Metadata to Sqlite3
I have a Django app, I am trying to upload the document to firebase. It uploads properly but the metadata does not upload to my sqlite3 database. def uploadProject(request): print("INSIDE UPLOAD VIEW") #Prints if request.method == 'POST': print("INSIDE POST REQUEST") #Does not print form = UploadProjectForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] file_url = upload_to_firebase(file) metadata = form.save(commit=False) metadata.file_url = file_url model metadata.save() return redirect('upload-project') else: form = UploadProjectForm() return render(request, 'base/upload_project.html', {'form': form}) This is my upload.js file that handles the form submission import { ref, uploadBytesResumable, getDownloadURL } from "https://www.gstatic.com/firebasejs/9.6.1/firebase-storage.js"; import { storage } from "./firebase-config.js"; document.querySelector('form').addEventListener('submit', async (e) => { e.preventDefault(); const fileInput = document.querySelector('input[type="file"]'); if (fileInput.files.length === 0) { alert('No file selected.'); return; } const file = fileInput.files[0]; const storageRef = ref(storage, `uploads/${file.name}`); const uploadTask = uploadBytesResumable(storageRef, file); uploadTask.on('state_changed', (snapshot) => { // Observe state change events such as progress, pause, and resume const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; console.log('Upload is ' + progress + '% done'); }, (error) => { // Handle unsuccessful uploads console.error('Upload failed:', error); }, async () => { // Handle successful uploads on complete const downloadURL = await getDownloadURL(uploadTask.snapshot.ref); console.log('File available at', downloadURL); } ); }); This is my … -
ModuleNotFoundError: No module named 'django' . Have tried most solutions including reinstalling
I'm currently trying to setup django for a website that rates music. Django is installed but when i run the code, the output says `File "c:\Users\nguye\Desktop\django_project\mymusicapp\mymusicapp\urls.py", line 17, in from django.contrib import admin ModuleNotFoundError: No module named 'django'`` I can run and visit the devlopment server but when i add /music/search to the end, it tells me "Using the URLconf defined in mymusicapp.urls, Django tried these URL patterns, in this order: admin/ The current path, music/search, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page." and in the terminal, it says "Not Found: /music/search. This is what I have in the urls.py `# mymusicapp/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('music/', include('music.urls')), How could I fix this? I cant seem to figure out whats wrong. I tried reinstalling django, tested the whole process on another device, so there must be something wrong in my process or code. -
Handling K8s forcefull kill of celery pods before completing running tasks
I am deploying a Django app with Celery workers on AWS EKS. I have everything running as expected, except that K8s proceeds to stopping Celery workers replicas before finishing ongoing tasks, I also have the same behavior when making a new deployment or pushing new code to the master branch. What I have tried: Setting a very large grace period, this solution didn't work, because we've got tasks that runs for hours. Setting a preStop hook, this solution didn't also work since K8s doesn't wait for the hook to finish if it exceeds the grace period. I have also tried fixed replicas count, but it's obviously not a solution. more information: I have celery setup with Redis as a messaging broker and a result backend. After some research I started considering using Keda, but upon reading the docs, seems like it will only allow me to scale Celery pods based on queues length but doesn't give the kill mechanism I am looking for. Is there any workaround to solve this issue? -
Data doesn't show on template - django
I have a chat app but it seems that i have a few mistakes which i don't know what is. Users can not see their chat history and their messages in the app. When Users write their messages on a specific form, I can see their messages on Django admin and that means the messages send successfully. But the problem starts in views.py, I tried a lot to address the template on chat history feed but when you run the app there is no response except: No chat history available. How can I fix this? We have models on models.py: # Main Imports # Django Imports from django.db import models from django.contrib.auth.models import User from django.utils import timezone # My Module Imports from authentication.models import BasicUserProfile # Chat # --------- class Chat(models.Model): creation_date = models.DateField(default=timezone.now) id = models.AutoField(primary_key=True) content = models.TextField() sender = models.ForeignKey( BasicUserProfile, on_delete=models.CASCADE, blank=True, null=True, related_name="sender" ) reciever = models.ForeignKey( BasicUserProfile, on_delete=models.CASCADE, blank=True, null=True, related_name="reciever" ) def __str__(self): return "chat: " + str(self.sender) ` and views.py: \`def chat_single(request, username): """ in this page users can chat with each other """ # admin user session pop # admin user session pop # Deleting any sessions regarding top-tier type … -
celery worker with sqs to consume arbitrary messages from outside
does anyone know if a celery worker can receive and consume messages from a sqs where the messages are pushed to the sqs by outside applications? I cannot find any resources on this. Another pointers would be appreciated. There are a lot of resources of connecting celery to sqs and then pushing tasks onto the queue and processing them but I want to push arbitrary messages (of different format) into the queue and have celery receive and process these in a task. Most resources online related to celery sending and receiving messages to sqs. -
Django: django.core.exceptions.SynchronousOnlyOperation while running scrapy script in django
I am trying to implement scrapy in django. For that this topic helped me. In my script I just return a simple object in order to see if everything work in order to be added in my model. I don't scrap any website. Issue myspider.py: from scrapers.items import ScrapersItem class ErascraperSpider(scrapy.Spider): name = "erascraper" allowed_domains = ["example.com"] start_urls = ["https://example.com"] def parse(self, response): return ScrapersItem(name="Argus") mypipeline.py: class ScrapersPipeline(object): def process_item(self, item, spider): item.save() print("pipeline ok") return item Also, I use Scrapy_DjangoItem in my items.py. Howerver I get this error: 2024-05-21 22:01:37 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://example.com> (referer: None) 2024-05-21 22:01:37 [scrapy.core.scraper] ERROR: Error processing {'name': 'Argus'} Traceback (most recent call last): File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/twisted/internet/defer.py", line 1078, in _runCallbacks current.result = callback( # type: ignore[misc] File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/scrapy/utils/defer.py", line 340, in f return deferred_from_coro(coro_f(*coro_args, **coro_kwargs)) File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/scrapers/scrapers/pipelines.py", line 14, in process_item item.save() File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/scrapy_djangoitem/__init__.py", line 35, in save self.instance.save() File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/django/db/models/base.py", line 822, in save self.save_base( File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/django/db/models/base.py", line 909, in save_base updated = self._save_table( File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/django/db/models/base.py", line 1071, in _save_table results = self._do_insert( File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/django/db/models/base.py", line 1112, in _do_insert return manager._insert( File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/django/db/models/query.py", line 1847, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/django/db/models/sql/compiler.py", … -
Django doesn't see relation in workflow tests
In normal tests running locally, but if I try to run them through workflows I get an error: Run chmod +x tests/test.sh Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "tours_data.city" does not exist LINE 1: ...ntry_id", "tours_data"."city"."point"::bytea FROM "tours_dat... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/runner/work/tours_manager/tours_manager/manage.py", line 22, in <module> main() File "/home/runner/work/tours_manager/tours_manager/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/site-packages/django/apps/registry.py", line 124, in populate app_config.ready() File "/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/site-packages/django/contrib/admin/apps.py", line 27, in ready self.module.autodiscover() File "/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/site-packages/django/contrib/admin/__init__.py", line 50, in autodiscover autodiscover_modules("admin", register_to=site) File "/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/site-packages/django/utils/module_loading.py", line 58, in autodiscover_modules import_module("%s.%s" % (app_config.name, module_to_search)) File "/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/runner/work/tours_manager/tours_manager/manager/admin.py", line 5, in <module> from .forms import AddressForm, ReviewForm File "/home/runner/work/tours_manager/tours_manager/manager/forms.py", line 40, in … -
Auth0 callback does not work on production
I have a React & Django application that works locally but not when deployed on Heroku. Long story short, on local env after login it makes a request to /authorize and after redirect to /callback?code=xxx&state=yyy and server respond with 200 OK. On prod, from the other hand, after calling /callback server gives 302 with Location to main page - “/”. No matter what page I will access, every time it gives 302 and falls into infinite loop. There are absolutely no difference between local and prod. Also, all necessary URLs are set up in env paths and Auth0 dashboard. This is my code for callback/index.tsx import { PageLoader } from "../../components/page-loader"; import { useEffect } from 'react'; import { useAuth0 } from '@auth0/auth0-react'; export default function Callback() { const { isAuthenticated, isLoading, error, loginWithRedirect } = useAuth0(); useEffect(() => { if (!isLoading && !isAuthenticated) { console.log("User is not authenticated. Redirecting to login..."); loginWithRedirect(); } }, [isLoading, isAuthenticated, loginWithRedirect]); if (isLoading) { return ( <div className="page-layout"> <PageLoader /> </div> ); } if (error) { return <div>Error: {error.message}</div>; } return ( <div className="page-layout"> <PageLoader /> </div> ); } I added it to App.js <Route path="/callback" element={<Callback />} /> providers/auth.tsx import { AppState, … -
How to deliver Django+ NextJs+ Postgresql project to client
I have my backend built on django and frontend on nextjs. I have to deliver it to client but I don't know how to do it. I have env folder in my django root directory which is virtual environment and I have made a requirements.txt file in the root of django project as well with .env file for secret keys. Also I have a folder named backend which contains tha next js project. It has package-json file in it. Do I have to make gitignore files in both directories if I am making the github push. And how can I deliver the project to the client I am a beginner. I tried transferring my virtual environment folder along with my project of django but the virtual environment didn't work correctly because it had directories with paths of my personal computer. What should I do... -
Azure Web App blocking AJAX requests to django application
I have a django (4.2.13 + python 3.10) application that at certain point makes AJAX requests to display progress to user while processing data from uploaded file. When I try this locally on my computer (linux) it works well and progress bar is updated from data received in response of AJAX calls. Similarly it also works on a test server (linux + nginx + gunicorn) and displays progress without hassle. On the browser side I use jQuery .post command to make calls. When I deploy same app to the Azure Web App it doesn't allow any of the calls to go through, all remain in Pending state in the browser and there is absolutely no trace anywhere in the Azure logs. Any hints? -
Best Download for Music [closed]
What is the best downloader like Spotify-DL or YT-DLP? Or even a Tidal downloader? I am just wondering because I am building my own music downloader because I am a DJ. I need good quality. I've used a Yt-dl once, and let me tell you it was bad. Which one do you recommend? -
Helm on Minikube showing an NGINX frontpage instead of a Django application
When I type minikube svc announcements-helm --url I get a URL that points me to a default NGINX page. I'm not sure why it is not showing me the actual Django application that is supposed to be there. I used kubectl exec to ls the pod, and it shows the application is inside the pod. I have the code for the Helm setup at this github repository: https://github.com/UCF/UCF-Announcements-Django/tree/helm/helm I'm fairly new to helm and kubernetes so any advice would be very appreciated