Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dockerized Django-React-PostgreSQL App Not Serving Frontend Despite Successful Build and Container Rebuild
I have a Dockerized application setup that includes a React frontend and a Django backend service. Despite successfully building the Docker container and ensuring the backend is running as expected, when I attempt to access the frontend, I'm met with the following message: 'This URL is only accessible after you've built the React frontend.' I've attempted to rebuild the Docker container from scratch to ensure there are no caching issues, but the problem persists. Environment: Operating System: Win10 -- Using Ubuntu through WSL for building the container Docker Version: Docker version 25.0.3, build 4debf41 Node Version: 10.5.0 Steps Taken: Rebuilding the Docker Container: I used the command docker build --no-cache -t mycontainer:latest . to ensure a fresh build without using any cached layers. Running the Container: After rebuilding, I ran the container using docker run -d -p 8000:80 --name mycontainer mycontainer:latest. Verifying Backend Functionality: I can confirm the backend services are running as expected, responding to API calls. Dockerfile: # Stage 0: Build React Frontend FROM node:16 AS build-frontend WORKDIR /app/frontend COPY frontend/package\*.json ./ RUN npm install COPY frontend/ . RUN npm run build # Stage 1: Build Django Application FROM tiangolo/uwsgi-nginx:python3.9 # Set environment variables ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 … -
Django Reuse Model Serializers Custom Validators
I have below serializer.py file. I have validate_semester() present in SubjectSerializer(), I want to reuse the same method in my StudentSerializer() class. Any help is appreciated. validate_semester() is verifying that semester id exists in semester table before assigning it to Student or Subject object. from rest_framework import serializers from .models import * from .helpers import SEMESTER_NOT_STORED class SemesterSerializer(serializers.Serializer): id = serializers.IntegerField(required=False) name = serializers.CharField(max_length=100, required=False) class SubjectSerializer(serializers.ModelSerializer): semester = SemesterSerializer() class Meta: model = Subject fields = ["id", "name", "code", "semester"] def create(self, validated_data): semester = validated_data.pop("semester") serializer = SemesterSerializer(semester) subject = Subject.objects.create( semester_id=serializer.data["id"], **validated_data ) return subject def validate_semester(self, value): id = value.get("id") semesters = list(Semester.objects.all().values_list("id", flat=True)) if id not in semesters: raise serializers.ValidationError({"id":[SEMESTER_NOT_STORED.format(id)]}) return value class SemesterSubjectSerializer(serializers.ModelSerializer): subjects = SubjectSerializer(many=True, read_only=True) class Meta: model = Semester fields = ["id", "name", "subjects"] class StudentSerializer(serializers.ModelSerializer): semester = SemesterSerializer() class Meta: model = Student fields = ["id", "name", "email", "semester"] def create(self, validated_data): semester = validated_data.pop("semester") serializer = SemesterSerializer(semester) student = Student.objects.create( id=None, semester_id=serializer.data["id"], **validated_data ) return student I have try adding validation at model level as well, it doesn't seem to be working out. I am getting IntegrityError anyways. from django.core.validators import MinLengthValidator, MaxLengthValidator from .helpers import SEMESTER_NOT_STORED def validate_semester(id): … -
Celery AppRegistryNotReady: Apps aren't loaded yet when using Django with Celery
I'm encountering an issue with Celery and Django where I receive an "AppRegistryNotReady" exception, stating that "Apps aren't loaded yet." This occurs when attempting to run Celery with the beat scheduler. Here are the key details: - I'm using Django with Celery for background task processing. - When trying to start the Celery beat scheduler using the command: celery -A myproject beat -l info I encounter the following traceback: Traceback (most recent call last): ... raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. - The issue seems related to Django settings or app loading during Celery initialization. This is my code celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE','myproject.settings') app = Celery('myproject') app.conf.enable_utc = False app.conf.update(timezone = 'Asia/Kolkata') app.config_from_object(settings, namespace = 'CELERY') # celery beat settings app.conf.beat_schedule ={ } app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') settings.py CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE ='Asia/Kolkata' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_RESULT_BACKEND = 'django-db' from myapp.models import Client,ImportSettings task_intervals = ImportSettings.objects.all() CELERY_BEAT_SCHEDULE = {} for task_interval in task_intervals: interval_seconds = task_interval.check_frequency_minutes client_id = task_interval.client CELERY_BEAT_SCHEDULE[f'import-{client_id}'] = { 'task': 'myapp.tasks.process_csv_files', 'schedule': interval_seconds, 'args': ( 'directory_path', 'table1', 'table2' ) … -
Gunicorn Worker Fails to Boot on Azure Web App Linux - ModuleNotFoundError
I am facing an issue with deploying a Django application on Azure Web App Linux using Gunicorn. The deployment process appears to be successful, but the Gunicorn worker fails to boot with the following error: [2024-03-07 04:42:30 +0000] [71] [ERROR] Exception in worker process ... ModuleNotFoundError: No module named 'csvvalidator.validator.wsgi' ... This is my YAML file: trigger: - main pool: vmImage: 'ubuntu-latest' steps: - task: UsePythonVersion@0 inputs: versionSpec: '3.10' addToPath: true - script: | python -m venv /home/site/wwwroot/antenv source /home/site/wwwroot/antenv/bin/activate pip install -r requirements.txt displayName: 'Install dependencies' - task: ArchiveFiles@2 inputs: rootFolderOrFile: '$(Build.Repository.LocalPath)' includeRootFolder: false archiveType: 'zip' archiveFile: '$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip' replaceExistingArchive: true - task: PublishBuildArtifacts@1 inputs: pathtoPublish: '$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip' artifactName: 'drop' publishLocation: 'Container' - task: DownloadBuildArtifacts@0 inputs: buildType: 'current' downloadType: 'single' artifactName: 'drop' downloadPath: '$(System.ArtifactStagingDirectory)' - task: AzureRmWebAppDeployment@4 inputs: ConnectionType: 'AzureRM' azureSubscription: 'Subscription' appType: 'webAppLinux' WebAppName: 'safe-lives-copilot-dev' packageForLinux: '$(System.ArtifactStagingDirectory)/**/*.zip' RuntimeStack: 'PYTHON|3.10' StartupCommand: 'gunicorn -b :8000 csvvalidator.validator.wsgi:application' The virtual environment is created during deployment, but there is a warning indicating that it couldn't find the virtual environment directory. 2024-03-07T04:42:30 WARNING: Could not find virtual environment directory /home/site/wwwroot/antenv. 2024-03-07T04:42:30 WARNING: Could not find package directory /home/site/wwwroot/__oryx_packages__. Any guidance or insights on resolving this Gunicorn worker boot failure would be highly appreciated. -
Getting a 404 on defined urls in django rest framework
I'm trying to access urls defined in django app (abcd). apps: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'rest_framework', "abcd", ] urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path('', include('abcd.urls')) ] abcd.urls from rest_framework import routers from abcd import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet, 'users') router.register(r'groups', views.GroupViewSet, 'groups') urlpatterns = router.urls views.py from rest_framework.viewsets import ViewSet class UserViewSet(ViewSet): pass class GroupViewSet(ViewSet): pass Whenever I try accessing: http://localhost:8000/users or http://localhost:8000/groups, I get a 404. -
How can I pass a Django url parameter to template's url method?
I have this urls.py file: ... urlpatterns = [ path('region_service_cost/<str:region>/', views.region_service_cost, name='region_service_cost'), path('monthly-region-service-cost/<str:region>/', views.monthly_region_service_cost, name='monthly-region-service-cost') ] And I have this views.py file: # Create your views here. from django.shortcuts import render from django.http import JsonResponse from .models import MonthlyRegionServiceCost def region_service_cost(request, region): return render(request, 'region-service-cost.html') def monthly_region_service_cost(request, region='global'): colors = ['#DFFF00', '#FFBF00', '#FF7F50', '#DE3163', '#9FE2BF', '#40E0D0', '#6495ED', '#CCCCFF', '#9CC2BF', '#40E011', '#641111', '#CCCC00'] labels = [ym['year_month'] for ym in MonthlyRegionServiceCost.objects.values('year_month').distinct()][:12] datasets = [] for ym in labels: for i, obj in enumerate(MonthlyRegionServiceCost.objects.filter(region=region, year_month=ym)): dataset = { 'label': obj.service, 'backgroundColor': colors[i % len(colors)], 'data': [c.cost for c in MonthlyRegionServiceCost.objects.filter(service=obj.service, region=region)] } datasets.append(dataset) return JsonResponse(data={ 'labels': labels, 'datasets': datasets }) and here is my region-service-cost.html file: {% extends 'base.html' %} {% block content %} <div id="container" style="width: 75%;"> <!-- canvas id="monthly-region-service-cost" data-url="{% url 'monthly-region-service-cost' %}/{{ region | urlencode }}/"></canvas --> <canvas id="monthly-region-service-cost" data-url="{% url 'monthly-region-service-cost' region=region %}/{{ region | urlencode }}/"></canvas> </div> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script> $(function () { var $productCostChart = $("#monthly-region-service-cost"); $.ajax({ url: $productCostChart.data("url"), success: function (data) { console.log(data); var ctx = $productCostChart[0].getContext("2d"); new Chart(ctx, { type: 'bar', data: { labels: data.labels, datasets: data.datasets, }, options: { plugins: { title: { display: true, text: 'Stacked Bar chart for pollution status' … -
Encryption for passing password from Frontend to backend in Django Application
I am working on Django Project and I want to setup authentication using LDAP backend. I have a form in UI where user will be able to enter user name and password and this will be passed to LDAP backend for authentication. While passing data from UI form to LDAP backend. DO I have to use any encryption technique? If yes, what kind of and how? Thank you. -
importing via Pandas CSV into Django model manytomanyfield
Total newbie to Django. I decided to put my hand up at work to develop a small POC app but cannot seem to get past importing csv data via Pandas into my Django model manytomanyField. Everything else is working except for the m2m field. Here is a portion of my model: class Service_Interval(models.Model): interval_name = models.CharField(null=True, max_length=200) class Task(models.Model): service_intervals = models.ManyToManyField(Service_Interval, related_name="intervals") Here is my View: def Import_Excel_pandas(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request. FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) #exceldata = pd.read_csv(filename, index_col ="Requirements") df=pd.read_csv('sheets/import_csv/'+filename, sep=',', usecols=['ID','Requirements','Service Intervals','Task Created']) #print(df) row_iter = df.iterrows() objs = [ Task( id = row['ID'], requirements = row['Requirements'], task_created = row['Task Created'], #service_intervals = row['Service Intervals'], << - dont work. ) for index, row in row_iter ] Task.objects.bulk_create(objs) Here in some of the CSV: enter image description here I think I need to connect to connect/create in Service_Interval first then add to Tasks inside the loop somewhere, but I'm stuck on how/where to add the code within the object task and if the process is correct. Any help would be appreciated as I've been stuck on this for a while now. intervals = row['Service Intervals'] … -
Issues with sending forgot passwords links with Django + AWS SES
I'm trying to add a feature on my Django App to send users who forgot their passwords a link to reset them via email. I'm not sure if I have set up my password reset email feature correctly, or if my AWS SES isn't configured to it. I have successfully sent email with a verified email in django shell with the method: send_mail('title','message','fromsender@mail.com',['toreciever@mail.com]) Which means that I have configured my environment variables correctly, but incase you need to see it: Here's my Django Settings.py: AWS_ACCESS_KEY_ID = env('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env('AWS_SECRET_ACCESS_KEY') EMAIL_BACKEND = 'django_ses.SESBackend' AWS_SES_REGION_NAME = 'us-east-2' AWS_SES_REGION_ENDPOINT = 'email.us-east-2.amazonaws.com' Here are my files views.py: from re import search from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import SignUpForm, AddRecordForm, RecordFilterForm, CustomUserChangeForm, CustomPasswordChangeForm from .models import Record from django.db.models import Q from django.views.decorators.http import require_http_methods from django.http import JsonResponse from django.contrib.auth.forms import UserChangeForm from django.core.exceptions import ValidationError from django.contrib.auth import update_session_auth_hash from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger #here is the homepage containing all the search filters def home(request): records = Record.objects.all().order_by('created_at') search_form = RecordFilterForm(request.GET) if search_form.is_valid(): search_query = search_form.cleaned_data.get('search') university_filter = search_form.cleaned_data.get('university_filter') course_name_filter = search_form.cleaned_data.get('course_name_filter') is_paid_filter = search_form.cleaned_data.get('is_paid') … -
django orm - multipule connections to postgesql
i have next code (django model) class AgentNmapTask(NmapTask): def execute(self): self.condition = ConditionTypes.LAUNCHED self.save() self.send_request_to_server('put', '/api/server/nmap/tasks/update/', { 'status': self.condition, 'id': self.id, 'count_of_launches': self.count_of_launches, 'next_run': self.next_run }) results, error = super().execute() if error: agent_nmap_result: AgentNmapResult = AgentNmapResult.objects.create(task=self, error=error) else: agent_nmap_result: AgentNmapResult = AgentNmapResult.objects.create(task=self, result=results) self.send_request_to_server('put', '/api/server/nmap/tasks/update/', { 'status': self.condition, 'id': self.id, 'count_of_launches': self.count_of_launches, 'next_run': self.next_run }) self.send_request_to_server('post', '/api/server/nmap/results/', {'nmap_task_id_on_agent': self.id, **model_to_dict(agent_nmap_result)}) i do next test for i in range(10): self.assertEqual(self.client.post( '/api/agent/nmap/tasks/', data={ 'ip_range': f'127.0.0.{i}', 'arguments': '-p0-1000 -Pn', 'company': f'test', }, format='json', ).status_code, 201) self.assertEqual(self.client.post( '/api/agent/nmap/tasks/', data={ 'ip_range': f'127.0.0.{i}', 'arguments': '-p0-1000 -Pn', 'company': f'test123', }, format='json', ).status_code, 201) def execute_task(agent_nmap_task): agent_nmap_task.execute() agent_nmap_tasks = AgentNmapTask.objects.all() executor = concurrent.futures.ThreadPoolExecutor(max_workers=10) future_tasks = [executor.submit(execute_task, agent_nmap_task) for agent_nmap_task in agent_nmap_tasks] concurrent.futures.wait(future_tasks) nmap_result_list = self.client.get('/api/agent/nmap/results/', format='json').json() self.assertEqual(len(nmap_result_list), 20) But when i start paralell processing by concurrent.futures.wait, python don't contunie test. Looks like it or postgesql locked . I see in "ps aux" next: postgres 65905 0.1 0.3 675020 29416 ? Ss 23:38 0:00 postgres: user test_scanner_db ::1(54510) idle in transaction postgres 65920 0.0 0.2 672076 19588 ? Ss 23:38 0:00 postgres: user test_scanner_db ::1(54408) INSERT waiting postgres 65922 0.0 0.2 672076 19576 ? Ss 23:38 0:00 postgres: user test_scanner_db ::1(54422) INSERT waiting postgres 65923 0.0 0.2 672076 19460 … -
How can I generate an annotated field with list of values in Django queryset?
I need to make up an advanced query that allows me get a queryset containing dictionaries with strings for keys and lists with all possible values for values. Here is what I got: ``` In [26]: Offer.objects.values('partner', 'partner_id') Out[26]: <QuerySet [{'partner': 'xex', 'partner_id': 'x_999'}, {'partner': 'xex', 'partner_id': 'x_888'}, {'partner': 'quiup', 'partner_id': 'q_888'}, {'partner': 'quiup', 'partner_id': 'q_777'}]> ``` Here is what I need to get: ``` <QuerySet [{'partner': 'xex', 'partner_ids': ['x_999', 'x_888']}, {'partner': 'quiup', 'partner_ids': ['q_888', 'q_777']} ``` I've tried annotations, F-expressions, `Value`, `.dictinct('partner')` but nothing brings me any closer. Any suggestions will be much appreciated and thank you very much for your attention. -
Issue with Django's LoginView after customizing User Model
I've encountered an issue after customizing Django's built-in User model (AbstractUser). I've created a custom user model named TheUser which inherits from AbstractUser. After making this change, the built-in LoginView from django.contrib.auth.views seems unable to authenticate users, even though the user data exists in the MySQL database. Here's a simplified overview of my code structure: models.py: from django.db import models from django.contrib.auth.models import AbstractUser from phonenumber_field.modelfields import PhoneNumberField # Create your models here. choices = ( ('M', 'Men'), ('F', 'Female'), ('P', 'Personnalised'), ) class TheUser(AbstractUser): age = models.IntegerField(blank=True, null=True) genre = models.CharField(max_length=10, choices=choices, default='M') adress = models.OneToOneField('UserAdress', on_delete=models.CASCADE, null=True) phone_number = PhoneNumberField(null=True) class UserAdress(models.Model): country = models.CharField(max_length=20) city = models.CharField(max_length=20) I've defined a custom user model named TheUser which includes additional fields like age, genre, phone_number, and a one-to-one relationship with UserAdress. urls.py: from django.urls import path, include from django.contrib.auth import views as auth_views from .forms import userForm form = userForm() app_name = 'user' urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='registration/login.html', context={'form': form}), name='login'), path('', include('django.contrib.auth.urls')), ] The login URL is configured to use Django's LoginView with a custom login template (login.html). Other URLs for signup, logout, and profile are also defined. forms.py: from django import forms from .models import TheUser from … -
relation "forum_forum" does not exist - Django Machina
I've been looking at documentation to install django-machina to use their forum capabilities. After following the quickstart guide I've run into an issue after makemigrations and migrate. relation "forum_forum" does not exist I've tried looking through the lib files of the package and doesn't seem to be wrong. I've tried to uninstall and reinstall but nothing has been working. """ Django settings for games_backend project. Generated by 'django-admin startproject' using Django 5.0.2. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from datetime import timedelta import environ import os from pathlib import Path from decouple import config from machina import MACHINA_MAIN_STATIC_DIR from machina import MACHINA_MAIN_TEMPLATE_DIR env = environ.Env( DEBUG=(bool, True) ) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent environ.Env.read_env(BASE_DIR / '.env') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'dasdddadsdadadsdd' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost'] CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', ] CORS_ALLOW_CREDENTIALS = True # Application definition INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.sitemaps', … -
i am recieving messages in my console but not in my notifications tab
i am using fcm to send push notificationsn in my django web app , i am recieving messages in my console but not in my notifications tab Message received. {from: '768143683456', collapseKey: 'campaign_collapse_key_3868676707069520118', messageId: 'c4a67ffd-5790-45a2-a339-64dad41dc i am tryng to get push notifications in laptop notifications but recieving only in console -
How to use ModelSerializer and serializer field on ModelSerializer?
serializer # serialize serializer = GetDealsResponseSerializer( data={ "deals": [model_to_dict(deal) for deal in deals], "is_remained": is_remained, } ) serializer.is_valid(raise_exception=True) # serializers class DealSerializer(serializers.ModelSerializer): area_for_exclusive_use_pyung = serializers.SerializerMethodField( "convert_square_meter_to_pyung" ) area_for_exclusive_use_price_per_pyung = serializers.SerializerMethodField( "calc_price_per_pyung" ) is_deal_canceled = serializers.SerializerMethodField("calc_is_deal_canceled") floor = serializers.SerializerMethodField("stringify_floor") def __init__(self, instance=None, data=..., **kwargs): super().__init__(instance, data, **kwargs) self.area_for_exclusive_use_pyung = None class Meta: model = Deal fields = ( "id", "deal_price", "brokerage_type", "deal_year", "land_area", "deal_month", "deal_day", "area_for_exclusive_use", "floor", "is_deal_canceled", "deal_canceled_date", "area_for_exclusive_use_pyung", "area_for_exclusive_use_price_per_pyung", "deal_type", "real_estate_id", ) def convert_square_meter_to_pyung(self, instance) -> Decimal: self.pyung = round( Decimal(instance.area_for_exclusive_use) / Decimal(3.305785), 2 ) return self.pyung def calc_price_per_pyung(self, instance) -> Decimal: return round(instance.deal_price / self.pyung, 2) def calc_is_deal_canceled(self, instance) -> bool: if instance.is_deal_canceled == "O": return True return False def stringify_floor(self, instance) -> str: self.floor = str(instance.floor) return self.floor class GetDealsResponseSerializer(DealSerializer): deals = DealSerializer(many=True) is_remained = serializers.BooleanField(required=False) class Meta: model = Deal fields = ( "id", "deal_price", "brokerage_type", "deal_year", "land_area", "deal_month", "deal_day", "area_for_exclusive_use", "floor", "is_deal_canceled", "deal_canceled_date", "area_for_exclusive_use_pyung", "area_for_exclusive_use_price_per_pyung", "deal_type", "real_estate_id", "deals", ) Error rest_framework.exceptions.ValidationError: {'deal_price': [ErrorDetail(string='This field is required.', code='required')], 'deal_year': [ErrorDetail(string='This field is required.', code='required')], 'land_area': [ErrorDetail(string='This field is required.', code='required')], 'deal_month': [ErrorDetail(string='This field is required.', code='required')], 'deal_day': [ErrorDetail(string='This field is required.', code='required')], 'area_for_exclusive_use': [ErrorDetail(string='This field is required.', code='required')], 'deal_type': [ErrorDetail(string='This field is required.', code='required')]} schema for … -
Debugger not stop on breakpoint
I'm trying to debug my Docker Django app with this configuration. launch.json: { "version": "0.2.0", "configurations": [ { "name": "Docker: Python - Django", "type": "python", "request": "attach", "connect": { "port": 5678, "host": "0.0.0.0", }, "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/project" } ], "django": true, "justMyCode": false } } docker-compose.debug.yml.py: ... django: extends: file: docker-compose.yml service: django command: sh -c "DEBUG_MODE=True python manage.py runserver 0.0.0.0:8000 --noreload" ports: - "5678:5678" manage.py: ... if os.environ.get("DEBUG_MODE", False): import debugpy debugpy.listen(("0.0.0.0", 5678)) debugpy.wait_for_client() I run docker compose with the debug file, the program waits to execute the vscode configuration but when I go to url the execution does not stop at the breakpoint. Output: Debugger warning: It seems that frozen modules are being used, which may make the debugger miss breakpoints. Please pass -Xfrozen_modules=off to python to disable frozen modules. Changing the command sh -c "DEBUG_MODE=True python -Xfrozen_modules=off manage.py runserver 0.0.0.0:8000 --noreload"doesn´t work either. Any sugestion? -
Second celery task in chain executing before database updates from first task are completed
I have a a chain of celery tasks and the second task needs to run, not just after the first task is complete, but after the database updates from the first task are complete. I've managed to get this working in my test by using a while loop to wait for the first chord in the chain to end but that seems wrong. I've tried other things like transaction.on_commit but that didn't work either. What's the right way to do this so that there isn't a race condition? # My simple model class TestModel(BaseModel): # The datetime the item occurred occurred_at = models.DateTimeField(null=False, blank=False, db_index=True) # A fake quantity quantity = models.DecimalField( max_digits=20, decimal_places=10, null=True, blank=True ) @shared_task def race_condition_tester() -> None: zulu = dateTime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ') workflow = chain( # This chord should asynchronously write a bunch of things to the database chord( generate_list_of_test_items.s( zulu=zulu, ), spawn_tasks_from_list_of_test_items_and_write_each_item_to_database.s(), ), # This should run after the chord, but also needs to run after the database # updates are complete test_if_items_are_in_database.s( zulu=zulu, ), ) workflow.apply_async() return None @shared_task def generate_list_of_test_items( results=None, zulu: str = None, ) -> List: logger.info(f"generate_list_of_test_items: {zulu=}") task_param_lists = [] for i in range(10): task_param_lists.append([i, zulu]) return task_param_lists @shared_task def spawn_tasks_from_list_of_test_items_and_write_each_item_to_database( … -
Django might not found api endpoint with slug
I have ViewSets with using action decorator. All actions with slug work. But there is one action which return Page not found class DefectImageViewSet(GenericViewSet): queryset = DefectImage.objects.all() serializer_class = DefectImageListSerializer @action( methods=['get'], detail=False, url_path='<uuid:defect_id>', # This method not work in current case, # but I using this definition method of slug everywhere # and it work # url_path=r'(?P<defect_id>[^/.]+)', # This is work in current case url_name='image-list' ) def get_list(self, request, defect_id): queryset: QuerySet = self.get_queryset() queryset = queryset.filter(defect_id=defect_id) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) I tried to remove slug and set default value and all work, but as soon as I add a slug, it returns Page not found -
Using django signals to update status of multiple models
I'm currently working on a Django project where I have models for ClientOrders, DesignerJob, and PrinterJob. I want to implement a functionality where changes in the status of DesignerJob and PrinterJob models trigger updates to the status of the associated ClientOrders model. For example, when the status of a DesignerJob changes from "new" to "in_progress," I want the status of the corresponding ClientOrders model to be updated to a specific status. Similarly, when the status of a PrinterJob changes, I want the associated ClientOrders status to be adjusted accordingly. I'm planning to use Django signals to achieve this, but I want to make sure I follow best practices and avoid potential pitfalls.Here are my specific questions: Signal Handling Approach: Should I use one signal for each model and implement all the conditions in that signal or make separate signals for each case? Circular Signal Calling: If I have a case where say PrinterJob signal updates DesignerJob status, will it cause circular calling? But this case is very unlikely. class ClientOrders(models.Model): franchise = models.ForeignKey( Franchise, on_delete=models.CASCADE, null=True) order_id = models.CharField(max_length=100, default=0 , unique=True) order_type = models.CharField(max_length=50, default='shop') payment_method = models.CharField(max_length=50, default='cash') card_no = models.CharField(max_length=16, default='', blank=True) expiry = models.CharField(max_length=50, default='', blank=True) … -
Error when trying to install Django using pip on Windows [duplicate]
I am new to Python and trying to install Django framework on my Windows machine using pip. However, I'm encountering the following error: pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + pip install django + ~~~ + CategoryInfo : ObjectNotFound: (pip:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException I'm not sure what this error means and how to resolve it. Can someone please guide me on how to fix this issue? Keep in mind that I'm a beginner and may need detailed instructions. Thank you in advance for your help! #python, #django, #pip, #windows, #installation, #beginner Its a screen-shot of erorr -
How do I load a django template using absolute paths?
I have a template xyz.html stored in the path /doc-templates/ so the full path is /doc-templates/xyz.html I'm trying to load the template using my_template = get_template('/doc-templates/xyz.html') But this raises the TemplateDoesNotExist exception. Any ideas before I roll out my own template loader? PS: Yes I know where Django templates should be, I just want to see if this is possible now that everything is being "dockerized" I have explicitly enabled django.template.loaders.filesystem.Loader and set the DIRS to a non empty list as documented but it seems to be ignoring the absolute path (possibly appending it to the DIRS list) -
django admin foreignkey icons not active
In the django admin (4.2) I can find in case of foreignkey fields the icons for editing, adding, deleting and viewing the relevant foreignkey element. However, only the add button is active in my case. How can I activate the other icons= -
Issue with Google login using Django allauth: Not prompted to select Google account in Incognito mode or certain browsers (opera, Edge)
I'm using Django allauth for Google login in my web application. Everything works fine, but I've encountered an issue where when users try to log in using Google in Incognito mode or with certain browsers like Opera or Edge, they are not prompted to select a Google account. Instead, it automatically logs in with the previously logged-in Google account. Here's a snippet of my settings in settings.py: SITE_ID = 1 SOCIALACCOUNT_ADAPTER = 'microdistribution.users.adapters.CustomSocialAccountAdapter' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' SOCIALACCOUNT_LOGIN_ON_GET=True ACCOUNT_LOGOUT_ON_GET = True SOCIALACCOUNT_EMAIL_AUTHENTICATION = True ACCOUNT_SESSION_REMEMBER = False SOCIALACCOUNT_PROVIDERS = { 'google': { 'AUTH_PARAMS': {'access_type': 'online'}, } } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'allauth.account.middleware.AccountMiddleware', #new 'microdistribution.utils.middleware.DynamicSiteMiddleware', #new ] INSTALLED_APPS = [ 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] Custom Adapter im using class CustomSocialAccountAdapter(DefaultSocialAccountAdapter): def save_user(self, request, sociallogin, form=None): user = sociallogin.user # Check if the user already exists existing_user = self.get_existing_user(user) if existing_user: return existing_user # If the user doesn't exist, create a new one try: new_user = super().save_user(request, sociallogin, form) new_user.name = sociallogin.account.extra_data.get('name') new_user.client_uid_id = User.objects.get(id = settings.CLIENT[request.META['HTTP_HOST']].client_uid_id) new_user.save() return new_user except Exception as e: print(f"Error While Creating User: {e}") return None def get_existing_user(self, user): existing_user = None try: … -
React & Django - WARNING:django.request:Forbidden: /api/user - SessionAuthentication
I'ved created this Django & React project (https://github.com/axilaris/docker-django-react-celery-redis), and I'm having difficulties with accessing API with SessionAuthentication. You can easily spin off with: docker-compose build docker-compose up I keep getting access issue with accessing /api/user (you can test with register, login) backend_container | Forbidden: /api/user backend_container | WARNING:django.request:Forbidden: /api/user You can look more the logs here: https://gist.github.com/axilaris/7b7a5c50f4f7112b440eaf8ef8100d9d In my django api code (backend/user_api/views.py): class UserView(APIView): permission_classes = (permissions.IsAuthenticated,) authentication_classes = (SessionAuthentication,) def get(self, request): serializer = UserSerializer(request.user) return Response({'user': serializer.data}, status=status.HTTP_200_OK) In settings.py: CORS_ALLOWED_ORIGINS = [ 'http://localhost', 'http://127.0.0.1', 'http://0.0.0.0', ] CORS_ALLOW_CREDENTIALS = True INSTALLED_APPS = [ .. 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] and in react: axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; axios.defaults.withCredentials = true; useEffect(() => { client.get("/api/user") .then(function(res) { setCurrentUser(true); }) .catch(function(error) { setCurrentUser(false); }); }, []); why whenever after I login and I reload back localhost on the browser it has forbidden /api/user and goes back to the login page. I feel the CORS are setup correctly and credentials are set true on both backend and frontend. -
Django Model Choice Form display logo + name
How to make a form populated from a database values to display the image from the URLField (team.logo) and the name (team.name) next to it. I am trying to achieve this through the following code but it ignores the image display part and only shows the team name: class TeamModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, team): return format_html(f'<img src="{team.logo}" class="form-logo">{team.name}') class TeamChoiceForm(forms.Form): teams_extra = Team.objects.all() team_home = TeamModelChoiceField( queryset=teams_extra, empty_label="Team Home" ) team_away = TeamModelChoiceField( queryset=teams_extra, empty_label="Team Away" )