Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting error in google sign in using javascript
when im trying to sign in through google I'm able to proceed but at this point its showing blank strong text {% block content %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="referrer" content="strict-origin-when-cross-origin"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="google-signin-client_id" content="my client id"> <title>Google Sign-In with JWT</title> <script src="https://accounts.google.com/gsi/client" async defer></script> </head> <body> <h1>Google Sign-In</h1> <div id="g_id_onload" data-client_id = "my client id" data-callback ="handleCredentialResponse" data-login-uri = "http://127.0.0.1:8000/user/login/" data-auto_prompt ="false"> </div> <div class="g_id_signin" data-type="standard" data-size="large" data-theme="outline" data-text="sign_in_with" data-shape="rectangular" data-logo_alignment="left"> </div> <script> console.log("Current origin:", window.location.origin); function handleCredentialResponse(response) { console.log("Received response from Google Sign-In"); const idToken = response.credential; console.log("ID Token:", idToken); fetch('http://127.0.0.1:8000/user/login/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }, body: JSON.stringify({ token: idToken }), credentials: 'include' }) .then(response => { console.log("Received response from server"); return response.json(); }) .then(data => { if (data.access) { console.log("JWT Token:", data.access); localStorage.setItem('jwt', data.access); alert('Login successful!'); } else { console.error("Login failed:", data); alert('Login failed!'); } }) .catch(error => { console.error('Error:', error); alert('An error occurred during login'); }); } window.onload = function() { console.log("Page loaded. Google Sign-In should initialize soon."); }; </script> </body> </html> tried everything but not move ahead using javascript more specifically HTML page to just get idToken from google and then sending it to backend … -
Restricting color options in Django admin form based on previously selected colors
I have two models, Product and Color, connected via ManyToManyFields. I want to restrict the color options available when editing a product in the Django admin interface. Models: class Color(models.Model): coid = ShortUUIDField(length=10, max_length=100, prefix="col", alphabet="abcdefgh") name = models.CharField(max_length=20) code = ColorField(default='#FF0000') product_varients = models.ManyToManyField('Product', related_name='color_variants', blank=True) image = models.ImageField(upload_to=color_directory_path, default="product.jpg") class Product(models.Model): pid = ShortUUIDField(length=10, max_length=100, prefix="prd", alphabet="abcdef") title = models.CharField(max_length=100, default="Apple") color = models.ManyToManyField(Color, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) Goal: When creating or editing a product, I want to restrict the colors in the color field to those that have been previously selected in the color field of the same product. In other words, I want the color field to show only colors associated with the product’s color, not all colors available in the database. What I Need: I want the color field in the Product admin form to display only the colors that are linked to the color of that product. If no color is set, I want the color field to be empty or show no options. Current Behavior: When I click on the color field in the Product admin form, it redirects me to the Color model, and then if I click on the … -
Unable to SSH using Public IP Address During Deployment in CI/CD Pipeline
I am setting up a CI/CD pipeline for my project, and during the deployment stage, I need to SSH into my server using a public IP address. However, I'm encountering an issue where the SSH connection times out when using the public IP Here's my setup: Public IP: xx.xxx.xxx.xxx Local IP: 192.168.31.234 SSH port: 22 (both internally and externally) What I've tried: Local network access: SSH works perfectly with the local IP (192.168.31.234) using the command: ssh sourov@192.168.31.234 Port forwarding setup on my router: External port: 22 Internal IP address: 192.168.31.234 Internal port: 22 Firewall settings: UFW is configured to allow SSH (port 22) on both IPv4 and IPv6: bash 22/tcp ALLOW Anywhere 22/tcp (v6) ALLOW Anywhere (v6) ssh sourov@xx.xxx.xxx.xxx Results in the error: ssh: connect to host 45.120.115.234 port 22: No route to host on: push: branches: - master pull_request: branches: - master jobs: test: runs-on: ubuntu-latest steps: - name: Check out repository uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v3 with: python-version: '3.12' - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run Django migrations run: python manage.py migrate working-directory : ./dining_manager - name : Run Django test … -
Django Admin: Limit ManyToManyField options based on previously selected ManyToManyField
I'm working on a Django project where I have two models, Product and Color. These two models are connected via ManyToManyFields. The relationship works fine, but I want to restrict the color options available when editing a product in the Django admin. My Models: from django.db import models from shortuuidfield import ShortUUIDField from colorfield.fields import ColorField from taggit.managers import TaggableManager class Color(models.Model): coid = ShortUUIDField(length=10, max_length=100, prefix="col", alphabet="abcdefgh") name = models.CharField(max_length=20) code = ColorField(default='#FF0000') product_varients = models.ManyToManyField('Product', related_name='color_variants', blank=True) image = models.ImageField(upload_to=color_directory_path, default="product.jpg") class Meta: verbose_name_plural = "colors" def __str__(self): return self.name class Product(models.Model): pid = ShortUUIDField(length=10, max_length=100, prefix="prd", alphabet="abcdef") title = models.CharField(max_length=100, default="Apple") main_product_color = models.ManyToManyField(Color, related_name='main_product', blank=True) color = models.ManyToManyField(Color, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) def __str__(self): return self.title Goal: Admin Behavior: When creating or editing a product, I want to restrict the colors in the color field to those that have been previously selected in the main_product_color field. In other words, I want the color field to show only colors associated with the product’s main_product_color, not all colors available in the database. What I Need: I want the color field in the Product admin form to display only the colors that are linked to the main_product_color … -
Why model instance is not being supplied to `ModelForm` inside a `DeleteView`
With Django 5.0.2, let's start with a simple model: from django.db import models class Book(models.Model): title = models.CharField(max_length=100) I want to do some form validation within ModelForm to determine whether or not the deletion should happen inside DeleteView. Simply put, I think the form is already capable of showing non-field errors and I want to avoid using messages.error() to sending back an error message. So I started with ModelForm: from django.forms import ModelForm class DeleteBookForm(ModelForm): class Meta: model = Book fields = [] def clean(self): super().clean() if not self.deletable(): self.add_error(None, 'This object can not be deleted') def deletable(self) -> bool: # do some evaluation on Book here book = self.instance if book.title == 'delete me please': return True else: return False and then the DeleteView: from django.views.generic import DeleteView from django.http import HttpResponseRedirect class DeleteBookView(DeleteView): model = Book form_class = DeleteBookForm def form_valid(self, form): self.object.delete() messages.success(self.request, 'The object has been deleted successfully.') return HttpResponseRedirect(self.get_success_url()) But self.instance appears to be None inside DeleteBookForm.deletable(). Indicating that the Book model instance is not being supplied/inserted to the ModelForm when it is being created. I believe this is not the case with UpdateView. Spent some time reading, I found this code on BaseDeleteView.post() (DeleteView's … -
django ORM query filter methods running multiple filter duplicates joins
I'm trying to run filters using methods in two separate attributes. In ICD10Filter: class Icd10Filter(filters.FilterSet): # New Filters for DOS Range dosFrom = filters.DateFilter(method='filter_by_dos_from', lookup_expr='gte') dosTo = filters.DateFilter(method='filter_by_dos_to', lookup_expr='lte') def filter_by_dos_from(self, queryset, name, value): return queryset.filter( base_icd__chart_review_dos__dos_from__gte=value ) def filter_by_dos_to(self, queryset, name, value): return queryset.filter( base_icd__chart_review_dos__dos_to__lte=value ) ICD10 filter is referenced in ChartReviewDx Model: class ChartReviewDx(models.Model): chart_review_dos = models.ForeignKey( ChartReviewDos, on_delete=models.SET_NULL, null=True, related_name="diagnosis_details" ) diagnosis_code = models.CharField(max_length=1024, null=True, blank=True) diagnosis_description = models.CharField(max_length=1024, null=True, blank=True) icd10 = models.ForeignKey("risk_adjustment.Icd10", on_delete=models.SET_NULL, null=True) base_icd = models.ForeignKey( "risk_adjustment.Icd10", on_delete=models.SET_NULL, null=True, blank=True, related_name="base_icd" ) and ChartReviewDx is referenced in ChartReviewDOS model: class ChartReviewDos(models.Model): chart = models.ForeignKey(Chart, on_delete=models.SET_NULL, null=True, blank=True, related_name="diagnosis") dos_from = models.DateField() dos_to = models.DateField() I want to fetch the ICD10 codes for particular DOS range only. The desired query is: SELECT distinct id, code, description FROM risk_adjustment_icd10 INNER JOIN healthcare_data_chart_review_dx ON ( id = healthcare_data_chart_review_dx.base_icd_id ) INNER JOIN healthcare_data_chart_review_dos ON ( healthcare_data_chart_review_dx.chart_review_dos_id = healthcare_data_chart_review_dos.id ) WHERE ( valid = 1 AND healthcare_data_chart_review_dos.dos_from >= '2023-08-19' AND healthcare_data_chart_review_dos.dos_to <= '2023-08-19' ) ORDER BY code ASC When I only run the filter for one of the fields, the query is working fine. But running filters on both fields give redundant JOINS and thus inaccurate results: The query … -
Django Celery with ALB on AWS persistent HTTP 502 Bad Gateway error
I can't figure out what's wrong in my setup. Frontend (HTTPS: 5173) docker container + django/celery (HTTPS: 8000, gunicorn) container on ec2. Both, 80 and 443 exposed. Loadbalancer with HTTPS:443 Listener, default target group to frontend, rule for /api/* path to Django https:8000. health check never works, no matter if http, https, path with trailing slash or without. self signed certificate works fine locally, worked fine just some days ago on aws imported for *.localhost/CN=localhost. expiry date > 100 days handshake test passes the logs from django/celery: [2024-10-18 09:33:25 +0000] [11] [WARNING] Invalid request from ip=172.31.xx.91: [SSL] PEM lib (_ssl.c:3900) [2024-10-18 09:33:41 +0000] [11] [WARNING] Invalid request from ip=172.31.xx.217: [SSL] PEM lib (_ssl.c:3900) [2024-10-18 09:33:43 +0000] [12] [WARNING] Invalid request from ip=172.31.xx.144: [SSL] PEM lib (_ssl.c:3900) [2024-10-18 09:33:49 +0000] [12] [WARNING] Invalid request from ip=172.31.33.xx: [SSL] PEM lib (_ssl.c:3900) [2024-10-18 09:33:55 +0000] [12] [WARNING] Invalid request from ip=172.31.xx.91: [SSL] PEM lib (_ssl.c:3900) parts from access logs ALB: ELB status code: 502 (Bad Gateway, indicating issues with the target or downstream services) SSL cipher and protocol: TLS_AES_128_GCM_SHA256 TLSv1.3 browser the same: index-BbUzq7eH.js:27 GET https://xxxxxxxxx.eu-central-1.elb.amazonaws.com/api/set-csrf/ 502 (Bad Gateway) Django ALLOWED_HOSTS is set to ["*"] for testing CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True … -
Issues with Running Django Management Command as an Always On Task on PythonAnywhere
I built and deployed my Django website on PythonAnywhere. I have a script in my app/management/commands/my_command.py that I intend to keep always running. I tried using the PythonAnywhere Always On Task feature for this, but the status never changes from "starting" to "running". There is no problem with the script itself because when I run: bash (venv) $ source /home/myusername/.virtualenvs/myenv/bin/activate && cd /home/myusername/myproject && python manage.py my_command the script runs successfully, and then when I go to my Always On Task console, I see that it ran successfully and was recorded in that console. But the problem is that I don't want to always manually run it in my Bash console. I have followed the instructions on the PythonAnywhere help page, and I have changed my task command to all the options I can use. I tried: bash source virtualenvwrapper.sh && workon myenv && python /home/myusername/myproject/manage.py my_command But it never changes to "running." I also tried: bash /home/myusername/.virtualenvs/myenv/bin/python /home/myusername/myproject/manage.py my_command Again, it never changes to "running." However, if I run the script in the Bash console, the Always On task prints out my success message! What am I doing wrong? -
Django + Crispy form - Readonly field for specific usergroup/user without Javascript : possible?
I know how to set a field readonly using the helper, but I'd like to disable values changes for specific users. The only way I found consists in adding a condition in the the form taking in account the user.is_staf or user.is_superuser. Form call in views.py s_form = stock_inline_formset( instance=product, form_kwargs={'empty_sst': empty_sst, 'user_is_staff': user.is_staff}) Condition in forms.py class SstStockForm(forms.ModelForm): class Meta: model = SstStock fields = ('qty', 'warehouse', 'maxsst', 'adresse', 'pua', 'cau') def __init__(self, *args, **kwargs): self.empty_sst = kwargs.pop('empty_sst', None) self.user_is_staff = kwargs.pop('user_is_staff', None) super().__init__(*args, **kwargs) if not self.user_is_staff: self.fields['qty'].widget.attrs = {'readonly': 'readonly'} self.fields['pua'].widget.attrs = {'readonly': 'readonly'} self.fields['cau'].widget.attrs = {'readonly': 'readonly'} [...] Is it the better way ? Otherwise I could do it with JS using the same condition based on the user for setting the input field readonly. I didn't find any ressource talking about this. -
Filtering Related Colors in Django Admin Based on Product Selection
Problem Statement: I am working on a Django project where I have two models: Product and Color. The Product model has a many-to-many relationship with the Color model through a field called product_varients. My goal is to filter the available colors in the Django admin interface based on the selected product. Specifically, I want to ensure that when creating or editing a Color, the product_varients field only shows colors that are not already associated with that product Models: Here are the relevant parts of my models: from django.db import models from shortuuid.django.fields import ShortUUIDField class Color(models.Model): coid = ShortUUIDField(length=10, max_length=100, prefix="col", alphabet="abcdefgh") name = models.CharField(max_length=20) product_varients = models.ManyToManyField('Product', related_name='color_variants', blank=True) def __str__(self): return self.name class Product(models.Model): pid = ShortUUIDField(length=10, max_length=100, prefix="prd", alphabet="abcdef") title = models.CharField(max_length=100, default="Apple") color = models.ManyToManyField(Color, blank=True) def __str__(self): return self.title Current Implementation: In my admin.py, I have implemented a custom form for the Color model to filter the product_varients field. Here’s the relevant code: class ColorAdminForm(forms.ModelForm): class Meta: model = Color fields = '__all__' def __init__(self, *args, **kwargs): super(ColorAdminForm, self).__init__(*args, **kwargs) if self.instance.pk: # Editing an existing color self.fields['product_varients'].queryset = Product.objects.exclude( color=self.instance # Exclude products that already have this color ) else: # Creating a new … -
Django IntegerField doesn't work as primary_key when CharField does for unmanaged model using custom DbManager
Working with Django5.0 updating a legacy oracle database with multiple DBs/Schemas. class OtherDbManager(models.Manager): def get_queryset(self): odb = "default" if hasattr(self.model, 'my_db'): odb = self.model.my_db return super().get_queryset().using(odb) class AAAModel(models.Model): class Meta: managed = False abstract = True objects = OtherDbManager() class BBBModel(AAAModel): class Meta(AAAModel.Meta): managed = False abstract = True my_db = 'bbb_db' class WackyObj(BBBModel): class Meta(BBBModel.Meta): managed = False db_table = '"%s"."%s"' % ("BBB_DB", "WACKY_OBJ") #myinteger = models.IntegerField(primary_key=True, null=False) #queryset operations fail if this is an integer field myinteger = models.CharField(primary_key=True, null=False) available_on = models.DateField() The underlying Oracle table "WACKY_OBJ" has filed MYINTEGER as NUMBER, NOT NULL. now if I do something like: target = WackyObj.objects.get(myinteger=8675309) I'll get my object back, but if I use an IntegerField instead (commented out in WackyObj class definition above): target = WackyObj.objects.get(myinteger=8675309) I'll get: wackymod.models.WackyObj.DoesNotExist: WackyObj matching query does not exist. Is this a bug? Also, in case it's relevant, i'm using a DatabaseRouter like so: from wackymod.models import AAAModel class XXXRouter: def db_for_read(self, model, **hints): if issubclass(model, AAAModel): return model.my_db return None def db_for_write(self, model, **hints): if issubclass(model, AAAModel): return model.my_db return None def allow_relation(self, obj1, obj2, **hints): return None def allow_migrate(self, db, app_label, model_name=None, **hints): return False As shown above, I've tried … -
Django login authentification with "allauth" and "dj_rest_auth" Unable to log in with provided credentials
I'm encountering an issue when trying to POST to http://127.0.0.1:8000/api/auth/login/. The error occurs when I include 'allauth' in my INSTALLED_APPS, but I need it for Google authentication. However, the login works correctly if I don't include 'allauth'. Any insights on how to resolve this would be greatly appreciated! this is the response by the api: { "non_field_errors": [ "Unable to log in with provided credentials." ] } this is the log from backend Bad Request: /api/auth/login/ [17/Oct/2024 09:56:13] "POST /api/auth/login/ HTTP/1.1" 400 68 The body of my request: { "email":"test@mail.com", "password":"******" } urls.py: from django.contrib import admin from django.urls import include, path, re_path from django.conf.urls.static import static from django.conf import settings from allauth.account.views import ConfirmEmailView from accounts.views import GoogleLogin, GoogleLoginCallback urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('app.urls')), path("api/auth/", include("dj_rest_auth.urls")), re_path( r"^api/auth/registration/account-confirm-email/(?P<key>[-:\w]+)/$", ConfirmEmailView.as_view(), name="account_confirm_email", ), path('api/auth/registration/', include('dj_rest_auth.registration.urls')), path("api/auth/google/", GoogleLogin.as_view(), name="google_login"), path( "api/auth/google/callback/", GoogleLoginCallback.as_view(), name="google_login_callback", ), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Setting.py: AUTH_USER_MODEL = 'app.CustomUser' MEDIA_URL = '/document/' MEDIA_ROOT = BASE_DIR INSTALLED_APPS = [ 'jazzmin', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_simplejwt', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'dj_rest_auth', 'dj_rest_auth.registration', 'app', ] SITE_ID = 1 REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(hours=1), … -
Django - access data in a model from a model with a foreign key
I have reduced code to display two models for simplicity. I am very new to Django and have been following the tutorial for the 2nd time but creating my own models. class Products(models.Model): product_name = models.CharField(max_length=50,unique=True,null=False) def __str__(self): return self.product_name class Current_tests(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) no_samples = models.IntegerField(default=0) stagecode=models.CharField(max_length=30,default="UPDATE REQUIRED") def __str__(self): return self.stagecode Where I have got a bit stuck is on how I access the data in my Products model using the foreign key in Current tests. For example I might want the product_name associated with a specific Current_test data row id or look product_name based on a stage code value. Equally, how do I get all stagecode for a given product_name. On the tutorial its done like this: q = Question.objects.get(pk=1) # Display any choices from the related object set -- none so far. >>> q.choice_set.all() <QuerySet []> https://docs.djangoproject.com/en/5.1/intro/tutorial02/ When I swap my classes in I get "AttributeError: 'Current_tests' object has no attribute 'product_name_set'. I have looked at many questions on here that suggest using "related name", "filter" but I have not been able to access data. Thanks -
Angular+Django how to access cookie under different domain
This is a follow up to my previous question (Angular+Django CSRF token not being saved as cookie) since I understand the underlying problem now. I have a Angular and Django setup and I am trying to get it to work with CSRF tokens. The way I have it set up is, Django includes a token in the response and it's saved as a cookie. Then my Angular interceptor gets the token from the cookie storage and includes it in the header of every subsequent request. This seems to be the only way that works and it works fine locally. The problem when I deploy the backend is that the returned cookie has a different domain (used to be localhost, now it's the name of the backend host). This means that the Angular cookie service isn't able to find it, so the requests have no CSRF token. I tried using HttpXsrfTokenExtractor instead, as proposed in https://www.stackhawk.com/blog/angular-csrf-protection-guide-examples-and-how-to-enable-it/. But that doesn't find the cookie either. I tried using the built-in Angular support for CSRF tokens (https://angular.dev/best-practices/security#httpclient-xsrf-csrf-security) but it doesn't include a token in any request regardless of the setup. Someone recommended reading the cookie manually from the backend response and then setting it … -
Starting a Django Web App as a Service using nginx and uWSGI fails
I have a simple web app that I am trying to run under Ubuntu 22.04 using Django, NGINX, and uWSGI. There is a service for my application which essentially starts uWSGI. If I start the service, uWSGI fails to start. If I run manually, it works perfectly. I can connect from a remote client and get the web page. So why am I having a problem running as a service? [uwsgi] chdir = /srv/dlnWebProject/dlnWebApplication module = dlnWebApplication.wsgi:application home = /srv/dlnWebProject/dlnWebApplication/.virtualenvs/dlnWebApplication master = true processes = 4 # Use HTTP socket http = 127.0.0.1:8000 # Or use a Unix socket with a full path die-on-term = true logto = /var/log/uwsgi/dlnWebApplication.log log-5xx = true log-4xx = true log-level = debug # Optional for more detailed logs Here is my service file: [Unit] Description=uWSGI instance to serve dlnWebApplication After=network.target [Service] User=www-data # Replace with the user that should run the service Group=www-data # Replace with the appropriate group WorkingDirectory=/srv/dlnWebProject/dlnWebApplication Environment="PATH=/srv/dlnWebProject/dlnWebApplication/.virtualenvs/dlnWebApplication/bin" ExecStart=/srv/dlnWebProject/dlnWebApplication/.virtualenvs/dlnWebApplication/bin/uwsgi --ini /srv/dlnWebProject/dlnWebApplication/uwsgi.ini --uid www-data --gid www-data [Install] WantedBy=multi-user.target This starts and runs uwsgi and allows remote clients to connect and responds with the web page: sudo -u www-data /srv/dlnWebProject/dlnWebApplication/.virtualenvs/dlnWebApplication/bin/uwsgi --ini /srv/dlnWebProject/dlnWebApplication/uwsgi.ini Starting as a Service gives: Oct 17 17:51:56 dlnServer systemd[1]: Started … -
Celery task completion check isn't checking the correct task
I'm new to celery, and I'm trying to have a task to process multiple orders in parallel. I used a chord, and send a the chord id back to the front-end to periodically check the task progress, however, the id I send is actually getting the results of the parent task that I nested the chord in? I'm not really sure what's wrong. Here is my parent task and Django endpoint @shared_task def bulk_create_shipping_labels_task(skus, carrier, service, measurements, user_id): start_time = time.time() logger.info(f"Starting bulk shipping label creation for SKUs: {skus}") orders = Order.objects.filter( Q(items__sku__sku__in=skus) & Q(order_status='pending_fulfillment') ).distinct().values_list('order_id', flat=True) # Create a chord of tasks header = [process_single_order.s(order_id, user_id, carrier, service, measurements) for order_id in orders] callback = collect_bulk_results.s() # Execute the chord chord_result = chord(header)(callback) print('chord_result', chord_result) end_time = time.time() total_time = end_time - start_time logger.info(f"Bulk shipping labels processing started. Total setup time: {total_time:.2f} seconds") chord_info = { 'id': chord_result.id, 'state': chord_result.state, 'ready': chord_result.ready(), 'successful': chord_result.successful(), 'failed': chord_result.failed(), } return { 'message': 'Bulk shipping labels processing started', 'task_id': chord_result.id, 'chord_info': chord_info } @api_view(['GET']) def check_bulk_shipping_status(request, task_id): logger.info(f"Checking status of bulk shipping task: {task_id}") try: task_result = AsyncResult(task_id) if task_result.ready(): result = task_result.get() print('result', result) return Response({ 'status': 'completed', 'message': 'All tasks … -
1 min delay in Vue.js rendering
So i have an application which has django as backend and vue.js on the frontend. This app intereacts with a source with websocket connection and this source continuosuly sends values to the application. whenever these values exceed any nominal state, those exceeded values are added in the symtomslist and the main page displays the updated values instantly, as the watch function of the page is set to watch on symptomslist. So the problem i have is, when we logged in and started the simulation, the app has been rendering the new values instantly when the values were changed, but after somrtime, even if the values were changed, the page has been rendering them after 1 min(even though different people logged in at different times, the lag in rendering started to all of us at the same time). we timed it multiple times and it measured 1 min each time. but when we logout and log back in, the state is again being rendered instantly. can you tell what might be causing this issue The console is logged every second. Maybe this is the issue? -
Pagination within Django - combining two projects
I am working off of two different projects. I have the Example By 5 and a YT series that I previously used to get started with Django. I liked the Pagination from the yt series so I decided to use that method, however in the Example By process, we moved from the Class base view to a function and now the pagination does not show up. I have added what I thought was needed in the view and html page but still getting nothing. VIEW code: def post_list(request, tag_slug=None): post_list = Post.published.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) post_list = post_list.filter(tags__in=[tag]) paginator = Paginator(post_list, 3) # 3 posts in each page page_number = request.GET.get('page') # Get the page number page_obj = paginator.get_page(page_number) context = {'page_obj': page_obj,'is_paginated': page_obj.has_other_pages()} # Check if pagination is needed try: posts = paginator.page(page_number) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request, 'blog/post/list.html', {'posts': posts, 'context' : context, 'tag': tag}) Here is the Pagination section of the html: {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number … -
Best Approach for Text Chunking in AI Chat Agent using React and Django (Langchain) without Sockets?
I’m currently building an AI chat agent that needs to handle text chunking and display responses word by word in real-time. My setup involves a React (frontend) and Django Langchain (backend) integration. I want to achieve this without relying on sockets to stream data and instead use an approach that can fetch and display responses as they are generated, ensuring the user sees a continuous flow of words. Here's a breakdown of my current setup: Frontend: React (with or without Redux) Backend: Django integrated with Langchain for handling the AI logic What I’m Looking For: Text chunking: Best practices for chunking AI responses (word by word or partial sentences) and updating the UI in React. Real-time updates: How to fetch and display this data incrementally (e.g., fetching a stream or chunks) without using sockets. Efficient handling: Strategies for making the experience smooth for users, especially on the frontend with React. I prefer not to use WebSockets and want to stick with traditional HTTP requests if possible. Looking for an approach that handles data/response chunking seamlessly so users get real-time updates without long waits. If anyone has experience with Langchain in this context or can share ideas on how to achieve … -
"Sign In Via Google" intermediary step in django-allauth
I am implementing Google OAuth into my Django project. I set up settings.py and everything, I got this <a href="{% provider_login_url 'google' %}">Continue with Google </a> link, but when I click it, it takes me to "http://127.0.0.1:8000/accounts/google/login/" page which looks like this: Only after clicking continue button I am redirected to the correct page when I can choose Google profile I want to log in with: How can I get rid of the intermediary step and go directly to selecting a Google profile after clicking the link? -
The list of urlpatterns should not have a prefix string
In Django 5.0 I get the error: The list of urlpatterns should not have a prefix string. My code is: from django.conf.urls import url from django.urls import path, include from django.contrib import admin app_name = 'AppServer_test' # specified as string literal rather than a variable urlpatterns = [ path('admin/', admin.site.urls), path('api/v1.0/user/', include('user_accounts.urls')), path('api/v1.0/notifications/', include('notifications.urls')), path('api/v1.0/feedback/', include('feedback.urls')), # path('', include('AppServer_test.urls')), # check that AppServer_test.urls is a valid and accessible module ] I've got the same code working in Django 3.2, the error only occurs in a system using 5.0 I've tried using round brackets instead of square as in this post: Django 1.11 url pattern error, how to solve? -
How to fix path lines order error in Django/Python?
I have strange error with urls.py file two lines: path('<slug:postcategory_slug>/<slug:slug>', post_detail, name='post_detail'), path('<slug:category_slug>/<slug:slug>', product_detail, name='product_detail'), If line with post_detail stands first view.product_detail render with error 404: No Post matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/pryamye-shlifmashiny/pnevmoshlifmashina-s150z66a Raised by: apps.blog.views.post_detail And view.post_detail works well But if line with product_detail stands first, like path('<slug:category_slug>/<slug:slug>', product_detail, name='product_detail'), path('<slug:postcategory_slug>/<slug:slug>', post_detail, name='post_detail'), view.product_detail works well But view.post_detail render with 404 error No Post matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/posts/pnevmaticheskij-udarnyj-gajkovert-at-238 Raised by: apps.store.views.product_detail Other config looks well, and URLS works PLS help me figure out what the problem is I do not know what the problem is, all the other files are fine, -
Issue in executing Django Server using python manage.py runserver
The following are the steps that I followed on my windows machine. pls let me know what the issue could be. And help me run my django server. Thanks a lot, Bhaskar Gundu PS C:\Windows\system32> .\MyVEnv2\Scripts\activate (MyVEnv2) PS C:\Windows\system32> django-admin startproject puddle django-admin : CommandError: 'C:\Windows\system32\puddle' already exists At line:1 char:1 + django-admin startproject puddle + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (CommandError: '... already exists:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError (MyVEnv2) PS C:\Windows\system32> cd puddle (MyVEnv2) PS C:\Windows\system32\puddle> ls Directory: C:\Windows\system32\puddle Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 10/17/2024 4:26 PM puddle -a---- 10/17/2024 4:27 PM 131072 db.sqlite3 -a---- 10/17/2024 4:26 PM 684 manage.py (MyVEnv2) PS C:\Windows\system32\puddle> python manage.py makemigrations No changes detected (MyVEnv2) PS C:\Windows\system32\puddle> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. (MyVEnv2) PS C:\Windows\system32\puddle> python manage.py runserver python : Watching for file changes with StatReloader At line:1 char:1 + python manage.py runserver + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (Watching for fi...th StatReloader:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError I tried executing following the required steps and am expecting to have a successful running of my Django Server. -
Django Summernote plugin upload image by userid
I am using the Summernote plugin for Django and my target is to allow users to upload media inside the server. At the moment files are organized (by default) in a folder named with the upload date. Something like: "ProjectName/media/django-summernote/2024-10-11/989d2f98-ad3c-47d6-9c07-e5f6d0c731e6.png" "ProjectName/media/django-summernote/2024-10-17/13d646b8-d7cd-4e04-a76a-804a1ee0d090.jpg". Is it possible to change the path and include the user_id in the path? Something like "ProjectName/media/django-summernote/User100/989d2f98-ad3c-47d6-9c07-e5f6d0c731e6.png" "ProjectName/media/django-summernote/User200/13d646b8-d7cd-4e04-a76a-804a1ee0d090.jpg". What I have done I made these edits in the settings.py file # Summernote plugin def summernote_upload_to(request, filename): user = request.user # Create the dynamic path upload_path = f'user_upload/{user}' return os.path.join(upload_path) SUMMERNOTE_CONFIG = { 'attachment_upload_to': summernote_upload_to, 'summernote': { 'attachment_filesize_limit': 200 * 1000 * 1000, # specify the file size 'width': '100%', 'height': '480', } } but, when I upload an image, I get an error AttributeError: 'Attachment' object has no attribute 'user' -
SMTP AUTH extension not supported by server in Django
Im being building an project using django framework and for now i wanted to test wether i can send emails to any users locally. So wrote this code in settings.py and got the error saying that SMTP AUTH extension not supported by server. So i researched everything but didnt find why this error has been raised and do smtp needs authentication? Please let know how i can solve this problem settings.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = config('EMAIL_HOST',cast=str, default = 'smtp.gmail.com') EMAIL_PORT = config('EMAIL_PORT',cast=str,default="587") EMAIL_USE_TSL = config('EMAIL_USE_TSL',cast=bool,default=True) EMAIL_USE_SSL = config('EMAIL_USE_SSL',cast=bool,default=False) EMAIL_HOST_USER = config('EMAIL_HOST_USER',cast=str,default=None) EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD',cast=str,default=None) ADMIN_USER_NAME = config('ADMIN_USER_NAME',default = "Admin user") ADMIN_USER_EMAIL = config('ADMIN_USER_EMAIL',default = None) MANAGERS = [] ADMINS = [] if all([ADMIN_USER_NAME, ADMIN_USER_EMAIL]): ADMINS += [ (f'{ADMIN_USER_NAME}', f'{ADMIN_USER_EMAIL}') ] MANAGERS = ADMINS Error im getting is this : Traceback (most recent call last): File "C:\Indraneel_coding\Django\Saas\src\manage.py", line 22, in <module> main() File "C:\Indraneel_coding\Django\Saas\src\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Indraneel_coding\Django\Saas\venv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Indraneel_coding\Django\Saas\venv\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Indraneel_coding\Django\Saas\venv\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "C:\Indraneel_coding\Django\Saas\venv\Lib\site-packages\django\core\management\base.py", line 459, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Indraneel_coding\Django\Saas\venv\Lib\site-packages\django\core\management\commands\sendtestemail.py", line 46, in handle mail_admins(subject, "This email was sent to the site admins.") File "C:\Indraneel_coding\Django\Saas\venv\Lib\site-packages\django\core\mail\__init__.py", line …