Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: count how many related objects I have
I have the following unmanaged django models: class A(models.Model): # some fields here class Meta: app_label = "app" db_table = "table_A" managed = False and another one, which has a foreign key to the model A: class B(models.Model): # some fields here city = models.CharField() obj_a = models.ForeignKey(A, on_delete=models.RESTRICT, related_name="b_objects") class Meta: app_label = "app" db_table = "table B" managed = False I need to write an endpoint that would return information about A objects + some statistics on B objects related to a particular A object: total number of B objects for this A object number of B objects for this A object where city='city_1' number of B objects for this A object where city='city_2' (results of 2 and 3 will add up to 1) Here's what I got so far (haven't tried to work on 2 and 3 bullets, as the 1st one isn't working yet): class MyView(ListAPIView): serializer_class = MySerializer queryset = A.objects.prefetch_related("b_objects").annotate( total=Count("b_objects") ).all() I got an error saying 'Cannot resolve keyword 'b_objects' into field.' Here's MySerializer: class MySerializer(serializers.ModelSerializer): cryovials = BSerializer(many=True) class Meta: model = A fields = "__all__" I found this question Django count related objects but unfortunately it didn't help me. -
Django system check to warn for deprecated blocks in templates
I am maintaining a Django library that has some templates that users can extend. I want to remove some of the blocks in a couple major versions and I was wondering if it is possible to add a system check to warn users who use that block in their code that it is now deprecated. The official Django documentation for system checks does not mention templates or blocks at all and I am not sure if it is possible (and if so, how) -
Error while trying to create a school timetable, in Django, that is automatically filled with buttons on the correct time and week day
I am trying to create a Django school timetable that is automatically filled with buttons once its created. I spent a lot of time trying to come up with a way since im still not very experience in programming and very new to Django, but the way I tried to do it was with "for" loops, while using a nested dictionary on the views, but due to my lack of understanding and experience i cannot figure out where the error (VariableDoesNotExist at /timetable/ Failed lookup for key [end_time] in 'monday') is comming from. this is my models.py of the schedule table(some stuff is in portuguese): class Horario(models.Model): ID_Horario = models.BigAutoField(primary_key=True) ID_Sala = models.ForeignKey(Sala, on_delete=models.CASCADE) ID_Turma = models.ForeignKey(Turma, on_delete=models.CASCADE) ID_Professor = models.ForeignKey(Professor, on_delete=models.CASCADE) Hora_inicio = models.TimeField() Hora_fim = models.TimeField() Dia_semana = models.CharField(max_length=100) Disciplina = models.CharField(max_length=100) this is my views page(where i would guess I did something wrong): def timetable(request): horario_entries = Horario.objects.all() timetable_data = {} for entry in horario_entries: day_of_week = entry.Dia_semana subject = entry.Disciplina start_time = entry.Hora_inicio.strftime('%H:%M') end_time = entry.Hora_fim.strftime('%H:%M') timetable_data[day_of_week] = {} timetable_data[day_of_week][start_time] = {} timetable_data[day_of_week][start_time][end_time] = {} timetable_data[day_of_week][start_time][end_time][subject] = {'entries': []} # Append the entry to the 'entries' list timetable_data[day_of_week][start_time][end_time][subject]['entries'].append(entry) return render(request, 'testetimetable.html', {'timetable_data': timetable_data}) and finally this … -
Undefined Movie Name and City Name in Seats HTML Template Despite Passing Through JavaScript and URL in Django Application
this is my html code of shows.html {% for cinema_hall in cinema_halls %} <div> <h2>{{ cinema_hall.name }}</h2> <div class="show-container" id="show-container-{{ cinema_hall.id }}"> <!-- Loop through shows for each cinema hall --> {% for show in shows %} {% if show.cinemahall == cinema_hall %} <div class="show-box" data-cinema_hall_id="{{ cinema_hall.id }}" data-show_id="{{ show.id }}"> Show: {{ show.timings }} <br> ₹ {{ show.price }} </div> {% endif %} {% endfor %} </div> </div> {% endfor %} and this is its js code function filterShowsByDate(date) { const movieName = '{{ movie_name }}'; // Replace with actual movie name const city = '{{ request.GET.city }}'; // Replace with actual city name $.ajax({ url: `/shows/${movieName}/filter/${date}/?city=${city}`, type: 'GET', success: function(response) { // Clear existing show containers $('.show-container').empty(); // Loop through the filtered shows and display them response.shows.forEach(function(show) { const showBox = `<div class="show-box" data-show-id="${show.id}" data-cinema-hall-id="${show.cinemahall_id}">Show: ${show.timings} <br> ₹ ${ show.price } </div>`; $('#show-container-' + show.cinemahall_id).append(showBox); }); $('.show-box').click(function(event) { event.preventDefault(); // Prevent default behavior const showId = $(this).data('show-id'); const cinemaHallId = $(this).data('cinema-hall-id'); const movieName = $(this).data('movie-name'); const cityName = $(this).data('city-name'); // Redirect to seats page with appropriate parameters window.location.href = `/seats/?show_id=${showId}&cinema_hall_id=${cinemaHallId}&movie_name=${encodeURIComponent(movieName)}&city_name=${encodeURIComponent(cityName)}`; }); }, error: function(xhr, errmsg, err) { console.log(errmsg); } }); } and this is views.py def filter_shows_by_date(request, movie_name, … -
Sorting Objects By Biggest Attribute Value Django
I am creating an application which will record Athletics events and points. Eventually I want to show on the screen the HOUSES (teams), points, and their overall position. The team with the highest number of points will be number one etc... My model has a field points which will be updated as results are recorded. I want the model to auto-determine he position of the team based off of the other objects' points. How can I achieve this? Here is my code: models.py class House(models.Model): name = models.CharField(max_length=255) points = models.FloatField(default=0, null=False) house_color = models.CharField(max_length=10, null=False, blank=False, default='red') position = models.IntegerField(default=4) def determine_position(self): all_houses_queryset = self.objects.all() I've tried to get the index of an ordered queryset on the template but it threw a Value error. Views.py def dashboard(request): ordered_houses = House.objects.all().order_by('-points').values() context = { 'houses': ordered_houses, 'range': [1,2,3,4], } return render(request, 'core/index.html', context) index.html {% for index, house in houses %} -
How to send (or upload ) images from flutter app to Django server and vice versa?
I want just the big picture on how to upload an image from a flutter app (.jpg or .png formats) to a Django server in order to classify the image and return a response, also how to send an from the server when the user in flutter app make a get request (I want just guidelines). I didn't tried yet because I don't know from where to start. -
Django SessionAuthentication 'Authentication credentials were not provided'
I'm using DRF for backend and React for frontend. I'm trying to get user Information after logged in. However, I got 403 'Authentication credentials were not provided' when sending get method to get the Information. The authentication method is SessionAuthentication. Here is the UserView which I got 403. class UserView(APIView): permission_classes = (permissions.IsAuthenticated, ) authentication_classes = (SessionAuthentication, ) def get(self, request): return Response(request.session['user_id'], status=status.HTTP_200_OK) I thought the user is authenticated after logged in. Is there anything I need to do before sending this request? In the response of login request, there is a sessionid. I checked that I set REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), } Also, I added below to the settings.py CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_SAMESITE = 'None' CORS_ALLOW_ALL_ORIGINS = False Here is the login class. class UserLogin(APIView): permission_classes = (permissions.AllowAny, ) authentication_classes = (SessionAuthentication, ) def post(self, request): data = request.data assert validate_email(data) assert validate_password(data) serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): user = serializer.check_user(data) login(request, user) request.session['user_id'] = user.user_id return Response(serializer.data, status=status.HTTP_200_OK) -
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