Django and Python "Questions and answers", page 3

27.10.2024
Django annotation for using left join

Models: class Operator_online(models.Model): name = models.TextField() role = models.TextField() class Reservations(models.Model): consultant_id = models.ForeignKey(Operator_online, on_delete=models.CASCADE) voip_number = models.IntegerField() Tried: consultants_operators = Operator_online.objects.filter( Q(role='consultant') | Q(role='support'), status='1' ) consultant_id_queryset = Reservations.objects.filter( consultant_id__in=consultants_operators ).select_related('consultant_id').annotate(role=F('consultant_id__role')).values( 'consultant_id', 'consultant_id__name', 'voip_number', 'role' ) Needs: …

27.10.2024
Как передать в форму параметр 'pk' другой модели

Выбираем категорию вопросов, рандомно берётся вопрос из этой категории, и, отображаются варианты ответов к этому вопросу. Проблема - не знаю как подать в форму 'pk' выбранного вопроса. models.py : from django.db import models class Category(models.Model): name = models.CharField(max_length=100) possible_ticket_numbers = …

27.10.2024
Identity - Django View that accepts both Auth and Non-Auth users

I have integrated Azure AD with Django using identity[django] package (docs). It provides a @login_required decorator that is used to restrict a view only for AD authenticated users. The view function decorated should accept an additional parameter …

27.10.2024
Unable to use Trigram search, despite it being installed

Hi I get issues with django being unable to run any trigram searches. I get errors such as django.db.utils.ProgrammingError: operator does not exist: unknown <<-> tsquery and django.db.utils.ProgrammingError: operator does not exist: character varying % tsquery and …

27.10.2024
How to set search paths for Heroku PostgreSQL database?

I'm currently deploying a Django app to Heroku, and my settings.py looks like this: if IS_HEROKU_APP: DATABASE_URL = dj_database_url.config( env="DATABASE_URL", conn_max_age=600, conn_health_checks=True, ssl_require=True, ) else: DATABASE_URL = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config('DATABASE_NAME'), 'USER': config('DATABASE_USER'), 'PASSWORD': config('DATABASE_PASSWORD'), 'HOST': config('DATABASE_HOST'), 'PORT': config('DATABASE_PORT'), …

26.10.2024
Code highlighting with Markdown, Pygments and CodeHiliteExtension in Django. Regular code blocks work nice, but inline code like `print("hi")` doesn't

I have a problem with Markdown, Pygments and CodeHiliteExtension in Django. I have a blog post written in Markdown, then I have a save function like that: def save(self, *args, **kwargs): # Convert Markdown to HTML with syntax highlighting …

26.10.2024
Cannot run my django project with apache (caught sigwinch, shutting down gracefully)

I am new to web development, I am trying to build a backend website with python django. I followed the tutorial on w3schools and built a django project, and now trying to deploy an apache server on aws ec2 server. …

26.10.2024
Сайт на django не может найти новость на сайте

Всем привет! Есть сайт на django, и страница детального просмотра новости. Но при переходе на детальный просмотр выдаёт ошибку. Код: urls.py from django.urls …

26.10.2024
Why does Django generate extra queries for related fields?

I am using drf and django-debug-toolbar. # model class Item(models.Model): title = models.CharField(max_length=255) description = models.TextField() owner = models.ForeignKey(User, on_delete=models.CASCADE) # serializer class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ["id", "title", "description", "owner"] view class …

26.10.2024
Django Chatroom model: Retrieve latest messages from all rooms a user is part of

I'm having a hard time constructing a query (sqlite) to get the latest message for each chatroom a user is part of. This is my model in Django: class Membership(models.Model): room_name = models.TextField() members = models.ManyToManyField(CustomUser, through="Message") class …

26.10.2024
How to add a default image to django ImageField with Amazon S3 for file storage?

I made a custom user model that contains an imagefield for the avatar: class User(AbstractUser): avi_pic = models.ImageField( upload_to='avi/', default='avi/default_avi.jpg') username = models.CharField(max_length=30, unique=True) bio = models.CharField(max_length=150, null=True, blank=True, default='') def __str__(self): return self.username I want to have a …

26.10.2024
How to filter datetime by day in django with timezone utc aware?

The datetime objects I am trying to filter are 2024-10-26 00:49:34.131805 in the database, which is 9pm in my country. what happens is that when I am trying to filter by day (created_at__day=timezone.now().day) it returns day 26, which is ok, …

26.10.2024
Why the email is not sending into my other email with that created object?

My idea is when someone submits the form and object created and my email verified in the settings with my app password sends an email to my other work email. My scenario is: Scenario: Omar Haji has a personal website …

26.10.2024
Unable to get multiple value in a django model

I am trying to get multiple values for a single label and that label will get two input values. I have added it successfully in the Django admin but when I send a request it gives me a string instead …

25.10.2024
Trouble Understanding how to create Custom User Model in Django

Here’s a brief overview of what I’ve accomplished so far, to ensure we're all on the same page. Please note that I’m still new to Django, so my approach might not be perfect or even close to what it should …

25.10.2024
Django Static Files Not Uploaded Properly to Digitalocean Spaces using S3

I am working on a django project v5.1 and as always I use digitalocean spaces for my static and media files. Here is the default configuration I always use: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Our …

25.10.2024
How to create an abstract GraphQL mutation in Wagtail (Django) with Graphene

I'm trying to make a mutation to create a page in Wagtail using graphene-django. The type of the created page should depend on passed parameters. All of the pages that are supposed to be created use the same input, which …

25.10.2024
Django: implement several different id numerations for foreign keys

I have a forum app, its structure is "forum -> subforum -> topic -> comments". Topics are special for each subforum and are not availiable from another subforum; the same for topics and their comments. Due to bad organization of …

25.10.2024
How to Sort values of a qury in Django based on the quantity of child table?

Hello guys i have a Product Class that have a child class ProductColors this is my two class : class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField(unique=True, allow_unicode=True) description = models.TextField() price = models.PositiveIntegerField() available …

25.10.2024
Django admin pannel redirect to /accounts/login/?next=/admin/

Whenever I open my django admin pannel it redirects to the following URL /accounts/login/?next=/admin/ I'm using DRF and all my DRF APIs running properly but my admin pannel is not opening every time it is redirecting to above URL. But …

25.10.2024
Django - Allauth doesnt use the custom signup form

I work with Django-Allauth and React as a FE. I added a parameter called name for for the Custom User I created, I've overridden the SignupForm in Forms.py to save it, and just like the documentation said I changed the …

25.10.2024
Any way to keep the cards always inside the background image?

I want the cards to remain inside of the background image no matter of the screen size, and it's not working with me. Here's my content code {% block content %} <style> .custom-skills-section { background: url('{{ background_image }}') center center …

25.10.2024
The events in fullcalendar sometimes duplicate on my database when moved to another date/time

I'm using fullcalendar 6.1.14 in django 4.2.11. I have a function defined to update the delivery date of an item where the number of the document of the item is the same as the event id, and the year is …

25.10.2024
Django ModelForm doesn't update instance but fails with IntegrityError

I'm having some really weird issue with a ModelForm. Instead of saving the instance, it attempts to create the instance with the same primary key. class Upload(models.Model): file = models.FileField(upload_to=get_foundry_upload_name, null=False, blank=False) filename = models.CharField(max_length=256, null=True, blank=True) foundry = models.ForeignKey(Foundry, …

25.10.2024
Django Under the Impression that I'm Missiing Positional Arguements

So Django is currently under the impression that I am missing positional arguments when I'm putting together a help section for a website. This includes help articles which are sourced from the Django model. Everything works as expected until I …

25.10.2024
Django check if a user is connected to wi-fi

I would like to check if a user is connected to wi-fi. If the user is connected to WiFi than they would be able to upload a video. If the user is not connected to WiFi than they would not …

25.10.2024
How to connect to a RabbitMQ cluster with Django?

In the documentation: https://github.com/Bogdanp/django_dramatiq/blob/master/django_dramatiq/apps.py It gives the following example: DEFAULT_BROKER = "dramatiq.brokers.rabbitmq.RabbitmqBroker" DEFAULT_BROKER_SETTINGS = { "BROKER": DEFAULT_BROKER, "OPTIONS": { "host": "127.0.0.1", "port": 5672, "heartbeat": 0, "connection_attempts": 5, }, "MIDDLEWARE": [ "dramatiq.middleware.Prometheus", "dramatiq.middleware.AgeLimit", "dramatiq.middleware.TimeLimit", "dramatiq.middleware.Callbacks", "dramatiq.middleware.Retries", "django_dramatiq.middleware.AdminMiddleware", "django_dramatiq.middleware.DbConnectionsMiddleware", …

25.10.2024
All users are displayed as "Active" even though they are supposed to be inactive, [closed]

List.html <p>Active Status: {% if datas.employee.is_active %}Active{% else %}Inactive{% endif %}</p> models.py class Employee(models.Model): is_active = models.BooleanField(default=True) def delete(self): self.is_active = True self.save() )

25.10.2024
Django Migration Error: admin.0001_initial is applied before its dependency users.0001_initial

I'm building a Django application with a custom user model, and I'm getting a migration error. I've already created my initial migrations but when trying to apply them, I get a dependency error. Error Message django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied …

25.10.2024
Sending an array from jQuery to a Django view

I am making a very small application to learn Django. I am send a nested array from jQuery and trying to loop it in my Django view. The jQuery code is as follows: $(document).on('click','#exModel',function () { const sending = []; …

25.10.2024
Detected dubious ownership in repository

I have a django project called my_project containing a database. In order to run the website with apache, I had to modify the access rights and ownership with sudo chown www-data:www-data my_project/ sudo chmod 755 my_project/ At least this …

25.10.2024
The image is not being stored in the media folder in Django, but the database contains the image name

Views.py employee = Employee.objects.create( user=request.user, # Assigning the current user first_name=request.POST.get('employee_firstname'), middle_name=request.POST.get('employee_middlename'), last_name=request.POST.get('employee_lastname'), email=request.POST.get('employee_email'), land_phone_number=request.POST.get('employee_landphone'), mobile_phone_number=request.POST.get('employee_mobile'), gender=request.POST.get('gender'), hire_date=request.POST.get('hire_date'), position=position, address=address, date_of_birth=request.POST.get('dob'), img=request.FILES.get('imgg'), # Make sure you're using request.FILES for image files ) models.py class Employee(models.Model): img = models.ImageField(upload_to='pics') …

25.10.2024
Azure App Service (oryx) does not use the set startup command

I want to deploy a Django DRF application to a azure App Service using artifacts (zip deployment) the artifact gets sucessfully uploaded from azure devops but the execution of the container fails since not all required packages are installed. Since …

25.10.2024
Why when I login in django, it throws error that username or password doesn't exists

I have this in terminal 'invalid_login': 'Please enter a correct %(username)s and password. Note that both fields may be case-sensitive.', 'inactive': 'This account is inactive.'} [ but, I have saved my username and password via browser, setting very common …

24.10.2024
Optimal Approach for Training an AI Model to Correct Errors in Multipolygon Coordinates (Django REST Framework GIS)

I need to select an AI model and a Python library that would be the most optimal for training. I have coordinates represented as a Multipolygon field from the djangorestframework-gis library, and they have small errors within different ranges—approximately 0.75 …

24.10.2024
Next.js Project Works in One Branch, API Requests Fail in Another

I'm working on a project using Next.js where I have two separate branches. The code works perfectly in one branch, but I'm encountering issues with API requests in the other branch. The code in both branches is almost identical, but …

24.10.2024
Upload file in background process in django drf (get this error : Object of type TemporaryUploadedFile is not JSON serializable)

This is my create function: def create(self,request,*args,**kwargs): serializer = ArchiveSerializer( data = request.data, context = {"request":request} ) serializer.is_valid(raise_exception=True) filename=serializer.validated_data.pop('file') serializer.save() id = serializer.validated_data.get("id") save_file_in_background.delay(id,filename) return Response(serializer.data, status=status.HTTP_201_CREATED) and this is the tasks.py from celery import shared_task from django.core.files.base …

24.10.2024
Django session doesn't work in Chrome Incognito mode

I have 3 views like this: def download_file(request, doc): if not request.session.get('is_authenticated'): return redirect(f"{reverse('pingfed_auth')}?next={request.get_full_path()}") return downloadfile(doc) def pingfed_auth(request): original_url = request.GET.get('next') or 'home' request.session['original_url'] = original_url return redirect('Some third party authentication') def redirect_pingfed_auth(request): if request.method == 'POST': request.session['is_authenticated'] = True …

24.10.2024
Django DB Foreign Key on_delete=CASCADE combined with null=True

What happens if a Django model contains both - on_delete=CASCADE and null=True: class MyModel(models.Model): ID = models.AutoField(primary_key=True) SomeInfo = models.BooleanField(default=False) SomeInfo2 = models.BooleanField(default=False) ID_FK1 = models.ForeignKey(OtherModel1, on_delete=models.CASCADE, null=True) ID_FK2 = models.ForeignKey(OtherModel2, on_delete=models.CASCADE, null=True) I see entries in the DB …

24.10.2024
Django-Nginx-React: How to fix ERR_CERT_COMMON_NAME_INVALID and Self-Signed Certificate Issues

I am working on a project using SimpleJWT tokens stored in HttpOnly cookies for authentication. The architecture involves a Django backend, an Nginx server, and a React+Vite frontend. Below is the configuration setup: I have created a self-signed Certificate …