Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx can not find static files in my docker instance
Hi I have a Django application that I'm preparing for deployment on a local network using docker. My Nginx proxy is unable to find the static files here is my docker-compose-deploy.yaml file: services: app: build: context: . volumes: - ./inventory/static:/vol/web/static - ./qr_codes:/vol/web/qr_codes proxy: build: context: ./nginx volumes: - static:/app/static/ ports: - "8080:8080" depends_on: - app db: image: postgres restart: always volumes: - ./data/db:/var/lib/postgresql/data ports: - "5432:5432" environment: POSTGRES_DB: Inventory POSTGRES_USER: postgres POSTGRES_PASSWORD: 123456 pgadmin: image: dpage/pgadmin4 restart: always ports: - "5050:5050" environment: PGADMIN_DEFAULT_EMAIL: jacob@me.com PGADMIN_DEFAULT_PASSWORD: 123456 PGADMIN_LISTEN_ADDRESS: 0.0.0.0 PGADMIN_LISTEN_PORT: 5050 volumes: static: postgres_data: here is my DockerFile for my Django app: # Use the official Python image from the Docker Hub FROM python:3.8-alpine # Set environment variables ENV PATH="/scripts:${PATH}" # Install dependencies COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers RUN pip install --no-cache-dir -r /requirements.txt RUN apk del .tmp # Create and set permissions for directories RUN mkdir -p /app/vol/web/static /app/vol/web/qr_codes RUN adduser -D user RUN chown -R user:user /app/vol RUN chmod -R 755 /app/vol # Copy project files COPY ./ /app WORKDIR /app COPY ./scripts /scripts RUN chmod +x /scripts/* # Set the user to 'user' USER user # Command to run the … -
On every api request list in add_where method get appended it is not resetting
I am trying to create custom manager in django rest framework that interacts with athena. Although I am facing strange issue that everytime I hit the endpoint with filters it gets appended in list where_conditions=[] on each request. It should not happen that actually makes the query that converts into SQL invalid. i want to reset the where_conditions list on each request. filter_class/base.py from apps.analytics.models.filter.fields.filter import FilterField from apps.analytics.models.filter.fields.ordering import OrderingField from apps.analytics.models.filter.fields.search import SearchField from apps.analytics.models.manager.query.utils import ModelQueryUtils class BaseFilterClass: _ordering_filter_query_key = "ordering" _search_filter_query_key = "search" def __init__(self, request): self._request = request @property def filter_params(self): if getattr(self.Meta, "filter_fields", None): req_query_params = {**self._request.query_params} for i in req_query_params: if isinstance(req_query_params[i], list): req_query_params[i] = req_query_params[i][0] if req_query_params and req_query_params.get("search"): del req_query_params["search"] req_query_params_key = set(req_query_params.keys()) valid_filter_params = self.Meta.filter_fields.declared_filter_params.intersection(req_query_params_key) params = {key: self.Meta.filter_fields.get_processed_value(key.split('__')[-1], req_query_params[key]) if "__" in key else req_query_params[key] for key in valid_filter_params} return ModelQueryUtils.FilterInput(params, ModelQueryUtils.FilterInput.JoinOperator.AND) @property def ordering_params(self): if getattr(self.Meta, "ordering_fields", None): req_query_params_ordering_params = self._request.query_params and self._request.query_params.get( self._ordering_filter_query_key) if req_query_params_ordering_params: declared_ordering_params = self.Meta.ordering_fields.declared_ordering_params return ModelQueryUtils.OrderInput( [str(param) for param in req_query_params_ordering_params.split(",") if ((param.startswith("-") and param[1:]) or param) in declared_ordering_params]) @property def search_params(self): if getattr(self.Meta, "search_fields", None): req_query_params_search_param = self._request.query_params and self._request.query_params.get( self._search_filter_query_key) params = {} if req_query_params_search_param: for key in self.Meta.search_fields.declared_search_params: params[key] = … -
i cant send email with aws-ses with python
setting.py = EMAIL_BACKEND = 'django_amazon_ses.EmailBackend' AWS_SES_REGION = env('AWS_SES_REGION') AWS_SES_SENDER_MAIL = env('AWS_SES_SENDER_MAIL') AWS_SES_SENDER = env('AWS_SES_SENDER') AWS_ACCESS_KEY = env('AWS_ACCESS_KEY') AWS_KEY_ID = env('AWS_KEY_ID') views.py = try: subject = f"Registration Confirmation for {event.title}" message = f""" Hello {request.user.username}, You have successfully registered for the event: {event.title} Event Details: Date: {event.date} Location: {event.location} Description: {event.description} Thank you for joining! """ send_mail( subject, message, settings.AWS_SES_SENDER_MAIL, [request.user.email], fail_silently=False ) return Response({ 'message': 'Event joined and email sent.', 'email_status': 'sent' }, status=status.HTTP_200_OK) except Exception as e: return Response({ 'message': 'Event joined but email could not be sent.', 'email_error': str(e) }, status=status.HTTP_200_OK) else: return Response({'error': 'Event member limit reached. Cannot join.'}, status=status.HTTP_406_NOT_ACCEPTABLE) I am trying to send an e-mail when a function runs in views.py. I get HTTP 200, although there is no problem in the code, my email is not delivered, but I do not receive any errors Can anyone help? -
How to bold text in template using django template tags
For example if I want to put an 'About' section or a 'Terms of Use' section in my website and want some of the subheadings to be bolded or made into headers. How could I use template tags to achieve this? My plan is to write the About section or Terms of Use in my models and use template tags to format the subheadings and any text that should be bolded. Is there a better way to do this? -
Django + React (Vite)
I’m currently trying to set up Django as a backend with React (using Vite) for the frontend, and I’m running into a few questions about the best way to get them working smoothly together. Has anyone done this and could share some advice? Specifically: What’s the most effective way to connect Django’s backend to a React frontend? Should I be focusing on Django REST framework for handling data, or are there other approaches that work well? How do you usually handle user authentication between Django and React, especially if social authentication is involved? Are there any good tutorials, articles, or videos you’d recommend for getting the whole setup right, including managing serialization, data flow, and development environments? Thanks so much for any help or pointers you can share! -
How to parse the result of applicant__count in Model.objects.values("applicant", 'counter').annotate(Count("applicant")) to counter field?
I have a model with these fields although there are other fields but this is my MRE: class Application(models.Model): applicant = models.ForeignKey(User, on_delete=models.CASCADE, to_field='email') company = models.CharField(max_length=100) counter = models.PositiveIntegerField(editable=False, default=0) I want to find the number of applications in the table for each applicant and parse the value automatically to the counter field. In my views.py, I have been able to use: model = Application.objects.values('applicant','counter').annotate(Count("applicant")) which returns correct values: {'applicant': 'test@users.com', 'counter': 1, 'applicant__count': 2} {'applicant': 'second@user.org', 'counter': 1, 'applicant__count': 4} But I am unable to extract the value of `applicant__count` and parse it directly to the counter field in models.py. I tried using the update, update_or_create method but I'm not able to update the model. I also tried django signals pre_save and post_save but they keep incrementing every value. For example, one applicant can have many job applications but instead of returning the total number of job applications for an applicant, django signals increments all the applications in the table. Is there any way to automatically save the result of `applicant__count` to my counter field? I would really appreciate any help. -
docker static files django not serving
I'm trying to set up my Django application in Docker with Nginx to serve static and media files, and Traefik to act as a reverse proxy. I've been struggling to get static and media files to load correctly, despite trying multiple configurations. I want Nginx to handle static and media files while Traefik manages the reverse proxy and SSL. Below is my docker-compose.yml file. docker-compose.yml # PostgreSQL Database Service db: image: postgres:16-alpine restart: unless-stopped environment: POSTGRES_USER: ${DATABASE_USER} POSTGRES_PASSWORD: ${DATABASE_PASSWORD} POSTGRES_DB: ${DATABASE_NAME} volumes: - postgres_data:/var/lib/postgresql/data - ./pg_hba.conf:/var/lib/postgresql/data/pg_hba.conf networks: - backend-network healthcheck: test: [ "CMD-SHELL", "pg_isready -U ${DATABASE_USER}" ] interval: 10s timeout: 5s retries: 5 deploy: resources: limits: cpus: '1.0' memory: 2G # Redis Cache Service redis: image: redis:7-alpine restart: unless-stopped command: [ "redis-server", "--appendonly", "yes", "--requirepass", "${REDIS_PASSWORD}" ] volumes: - redis_data:/data networks: - backend-network healthcheck: test: [ "CMD", "redis-cli", "-a", "${REDIS_PASSWORD}", "PING" ] interval: 10s timeout: 5s retries: 5 deploy: resources: limits: cpus: '0.5' memory: 512M # Django Web Application Service web: image: ganiyevuz/tana-backend:latest restart: unless-stopped command: > /bin/bash -c " ./wait_for_db.sh db 5432 && python manage.py collectstatic --noinput && python manage.py migrate && gunicorn conf.wsgi:application --bind 0.0.0.0:8000 --workers 4 --threads 4 " volumes: - static_volume:/app/static - media_volume:/app/media expose: - "8000" … -
Best practices for using @property with Enum values on a Django model for DRF serialization
Question: I'm looking for guidance on using @property on a Django model, particularly when the property returns an Enum value and needs to be exposed in a Django REST Framework (DRF) serializer. Here’s my setup: I’ve defined an Enum, AccountingType, to represent the possible accounting types: from enum import Enum class AccountingType(Enum): ASSET = "Asset" LIABILITY = "Liability" UNKNOWN = "Unknown" On my Account model, I use a @property method to determine the accounting_type based on existing fields: # Account fields ... @property def accounting_type(self) -> AccountingType: """Return the accounting type for this account based on the account sub type.""" if self.account_sub_type in constants.LIABILITY_SUB_TYPES: return AccountingType.LIABILITY if self.account_sub_type in constants.ASSET_SUB_TYPES: return AccountingType.ASSET return AccountingType.UNKNOWN In Django views, I can use this property directly without issues. For example: account = Account.objects.get(id=some_id) if account.accounting_type == AccountingType.LIABILITY: print("This account is a liability.") Problem: When trying to expose accounting_type in DRF, using serializers.ReadOnlyField() does not include the property in the serialized output: class AccountDetailSerializer(serializers.ModelSerializer): accounting_type = serializers.ReadOnlyField() class Meta: model = Account fields = ['accounting_type', 'account_id', ...] I found that switching to serializers.SerializerMethodField() resolves the issue, allowing me to return the Enum value as a string: class AccountDetailSerializer(serializers.ModelSerializer): accounting_type = serializers.SerializerMethodField() class Meta: model … -
minio.error.S3Error: S3 operation failed; code: AccessDenied with root user access key
I have docker cluster with several containers such as minio as file storage and backend on django and it roughly looks like this: files: image: minio/minio container_name: files env_file: .env command: server /data --console-address ":9001" healthcheck: test: curl -I ${MINIO_EXTERNAL_ENDPOINT}/minio/health/live interval: 5s timeout: 5s retries: 5 volumes: - s3:/data ports: - 9000:9000 - 9001:9001 backend: build: ./backend container_name: backend env_file: .env volumes: - ./scripts/backend:/app/scripts healthcheck: test: curl --fail ${BACKEND_HC} || exit 1 interval: 10s timeout: 5s retries: 5 ports: - 8000:8000 depends_on: files: condition: service_healthy Everything was OK until today, when my SSD died and i was forced to use the older one. It has only 119 Gb of "real" space so i did Troubleshoot -> Purge Data in docker desktop (curse you, wsl/docker). And then cloned my project expecting it to start as usual. And then i was hit with the error in title. Here is useful part of stack trace: backend | [2024-11-13 15:50:41 +0700] [13] [INFO] Worker exiting (pid: 13) backend | [2024-11-13 15:50:41 +0700] [14] [ERROR] Exception in worker process backend | Traceback (most recent call last): ... backend | application = get_wsgi_application() backend | ^^^^^^^^^^^^^^^^^^^^^^ backend | File "/usr/local/lib/python3.11/site-packages/django/core/wsgi.py", line 12, in get_wsgi_applicati on backend … -
PyCharm 2024.2 not running Django tests correctly
Our project has extensive unit tests derived from rest_framework.test's APITestCase. This has always worked well - right-clicking on any Test file, class, or method, and selecting run has always generated a test configuration which has run the test effectively. But with the release of PyCharm 2024.2, this has mysteriously stopped working. I'm wondering if I'm overlooking a configuration setting or file somewhere. I have 2024.1.7 and 2024.2.4 both installed currently. In 2024.1.7, the test command issued by PyCharm is of this form, which works: python -u /home/vagrant/.pycharm_helpers/pycharm/django_test_manage.py test tests.api.test_my_code.MyCodeTest /opt/my-project-path In 2024.2.4, I get this command instead: python -u /home/vagrant/.pycharm_helpers/pycharm/django_test_manage.py /opt/my-project-path tests.api.test_my_code.MyCodeTest /Users/apollo/code/my-project-path I'm using a Vagrant virtual machine on my Mac to run my local server code. /opt/my-project-path is the path in the virtual server, while /Users/apollo/code/my-project-path is the path on my Mac. But more importantly, where did the word test go in this command, and how do I get it back?? The django_test_manage.py execution quite sensibly responds with: Unknown command: '/opt/my-project-path' -
Django REST & react-admin: Content-Range header missing
Using react-admin's ra-data-simple-rest DataProvider I would like to make a request to a django REST api. In Django I built the following custom pagination class which is supposed to expose the Content-Range header required by the DataProvider: from rest_framework import pagination from rest_framework.response import Response class ContentRangeHeaderPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): total_items = self.page.paginator.count # total no of items in queryset item_starting_index = self.page.start_index() - 1 # In a page, indexing starts from 1 item_ending_index = self.page.end_index() - 1 content_range = 'posts: {0}-{1}/{2}'.format(item_starting_index, item_ending_index, total_items) headers = {'Content-Range': content_range} return Response(data, headers=headers) In Django settings I put the following: INSTALLED_APPS = [ ... 'corsheaders', 'rest_framework', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': '<myProject>.pagination.ContentRangeHeaderPagination', 'PAGE_SIZE': 10 } CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:5173', ] CORS_ALLOW_HEADERS = ( "accept", "range", "content-range", "authorization", "content-type", "user-agent", "x-csrftoken", "x-requested-with", ) I keep getting the Error "The Content-Range header is missing in the HTTP Response. The simple REST data provider expects responses for lists of resources to contain this header with the total number of results to build the pagination. If you are using CORS, did you declare Content-Range in the Access-Control-Expose-Headers header?" Any ideas what I am doing wrong? Unfortunately the ra-data-django-rest-framework Data … -
Django : Update sqlite database from html template
I've a database table called 'FormDB. I've written a program for CURD operation. For each row of db data there're two buttons 'EDIT' and 'DELETE'. The edit button is functioning when i give <form action = "" method = "POST"> in the HTML template. but when I redirect to the page where all the db data is showing, it's creating a new row of data instead of updating the existing value. view.py def EditData(request, id): a = FormDB.objects.get(id=id) nameupdate = a.name form = DjangoForm(request.POST) if request.method == "POST" and form.is_valid(): newname = form.cleaned_data['name'] b = FormDB.objects.get(id=id) b.name = newname b.save() return render(request, "editform.html", {'nameupdate' : nameupdate}) editform.html <body> <h1>EDIT PAGE</h1> <form action = "" method = "POST"> {% csrf_token %} {% if nameupdate %} <label>Enter new name: </label> <input type="text" name = "name" placeholder = {{ nameupdate }} REQUIRED> <input type="submit" value = "Submit Changes" ><br> {% endif %} </form> So, when I click on Submit Changes, it should redirect to the page where all dbdata is showing with updated value. -
How can I implement email verification in Django
Completely stumped! I'm using the console as my email backend. I end up with False in token_generator.check_token as a result Invalid or expired token. is displayed in my homepage when I navigate to say http://localhost:8000/user/verify-email/?token=cgegv3-ec1fe9eb2cebc34e240791d72fb10d7d&email=test16@example.com Here's my code from django.contrib.auth.tokens import PasswordResetTokenGenerator class CustomPasswordResetTokenGenerator(PasswordResetTokenGenerator): pass # Define a single instance of the token generator token_generator = CustomPasswordResetTokenGenerator() def verify_email(request): email = request.GET.get("email") token = request.GET.get("token") try: user = CustomUser.objects.get(email=email) except CustomUser.DoesNotExist: messages.error(request, "Invalid verification link.") return redirect("home") if token_generator.check_token(user, token): user.is_active = True user.save() messages.success(request, "Your email has been verified!") return redirect("sign_in") else: messages.error(request, "Invalid or expired token.") return redirect("home") from django.core.mail import send_mail from django.urls import reverse from user_management.utils import token_generator def send_verification_email(user, request): token = token_generator.make_token(user) verification_url = request.build_absolute_uri( reverse("verify_email") + f"?token={token}&email={user.email}" ) send_mail( "Verify your email", f"Click the link to verify your email: {verification_url}", "no-reply@example.com", [user.email], fail_silently=False, ) -
Django filter not working when using F() with ManyToMany
I have the following query: MyModel.objects.filter(foreing_key__value=F('value')) And It works perfectly. But now I have some complex rules where I need to evaluate the ForeignKey value depending on some conditions. Just to simplify, if I refactor the query to: MyModel.objects.annotate( valid_value=F('foreing_key__value') ).filter( valid_value=F('value') ) It doesn't work when the foreing_key__value is NULL. Why is this happening? I think it's related to LEFT JOIN, which is not applied when using the F() operator, but I'm unsure how to fix this issue. Thanks in advance -
Django project domains
I'm trying to figure 1) if Django can do these things and 2) if it can, should I? I'm thinking it is easier to manage just 1 project vs multiple, but I don't know exactly what Django is capable of yet... If I have my main application at example.com and say I begin a blog about the application at blog.example.com. Can I use one Django project for that or do I need to have 2 Django projects. One to handle example.com and the other to handle blog.example.com? Note: I will be using DRF in this project and I don't know if that makes a difference? -
Multiple different forms in a view Django
I was wondering if there was a way to have multiple different forms in a single view and to press a single submit button for the information to be stored. I have the following forms, the first one is my general form that should be created first: class GeneralForm(forms.ModelForm): name = forms.CharField(max_length=50) TYPE_CHOICES = ( ("C","C"), ("E","E") ) STATUS_CHOICES = ( ("A", "A"), ("F", "F"), ) type=forms.ChoiceField(choices=STATUS_CHOICES) number=forms.CharField(max_length=50) TURN_CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3") ) turn = forms.ChoiceField(choices=TURN_CHOICES) class Meta: model = models.General fields=["name","type","number","turn"] The second one needs an instance of the first one and so does the third: class TypeOneForm(forms.ModelForm): num_chairs=forms.IntegerField() num_instalations = forms.IntegerField() total = forms.IntegerField() num_programs = forms.IntegerField() class Meta: model = models.TypeOne fields=["num_chairs","num_instalations","total","billetes_cien"] class TypeTwoForm(forms.ModelForm): num_available_seats=forms.IntegerField() num_available_instalations = forms.IntegerField() total = forms.IntegerField() num_new_programs = forms.IntegerField() class Meta: model = models.TypeTwo fields=["num_available_seats", "num_available_instalations","total","num_programs" ] I was reading I could use FormSets but im not sure if i can use different forms instead of multiple instances of the same form -
I am actually working on the route integration with my personal web site || Is there any available public api for YouTube [closed]
I needed to integrate the YouTube with my personal website backend. Is there any public api available for the same. Thanks.... The API is required to integrate. So that can call to the api & get the data of the relevant YouTube videos.. -
Django not found in Github actions
I have the following CI pipeline defined in Github Actions. It is using the same container as which the production server is using. The pipeline was running fine last week, but this week it suddenly stopped working. Some observations from the run logs: We start with upgrading pip, but this doesn't seem to happen The dependencies are installed correctly, but it gives a warning that pip can be upgraded Running fake migrations immediately fails with ModuleNotFoundError: No module named 'django'. Any ideas how I can debug this to investigate what is going wrong? test_project: runs-on: ubuntu-latest container: image: python:3.11-slim strategy: max-parallel: 2 matrix: python-version: [ "3.11" ] services: postgres: image: postgres:14 env: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres ports: - 5432:5432 options: >- --health-cmd "pg_isready -U postgres" --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install -r requirements-test.txt - name: Check missing migrations run: python project/manage.py makemigrations --check --dry-run --settings project.settings.local - name: Run Tests run: pytest --cov=project project/ -
How to apply a django filter only if both field have a value
I have a simple django filters interface like this This is how I wrote the filters, but of course it is wrong because it adds the filter even when i choose only one field. Also I'm sharing the same FilterSet for both. tipo_oid = filters.ChoiceFilter(label='Tipo Identificativo', choices = TipoOid.objects.all().values_list("id","denominazione").exclude(annullato=True).filter(id__in=[2,3,12,22,9,49]).order_by('denominazione'), method='filter_ide') identificativo = filters.CharFilter(label='Identificativo', method='filter_ide') def filter_ide(self, queryset, name, value): if name == 'tipo_oid': filtroPfIdInPfIde = PfIdentificativi.objects.filter(pf_id=OuterRef('id')).filter(tipo_oid=value).exclude(annullato=True) queryset = queryset.filter(Exists(filtroPfIdInPfIde)) if name =='identificativo': filtroIdeInPfIde = PfIdentificativi.objects.filter(pf_id=OuterRef('id')).filter(identificativo=value).exclude(annullato=True) queryset = queryset.filter(Exists(filtroIdeInPfIde)) I need to ignore if only one of the fields have a value and to apply filter() to the queryset only once and only if both have a value. How would you do that? Now even if I would use two separate filters, the result would not be the one I'd like. I think I could just do it in the viewSet, but it's not what I want because I want to do it in the Filter. -
How to adjust the size of help_texts in Django form?
I'm trying to adjust the size of help_texts field of 'username'. I don't understand where should apply the styling. class SignUpForm(UserCreationForm): password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Password'}), label='') password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Confirm Password'}), label='') class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'phone'] widgets = { 'username': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Username'}), 'email': forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Email Address'}), 'phone': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Phone Number'}), } labels = { 'username': '', 'email': '', 'phone': '' } help_texts = { "username": "Must contain only letters, numbers, hyphens and underscores.", } -
SSL issue in django web application
I am working on a django web application in python and I use docker containers. My ssl certificate has expired and I want to get a signed certificate from a domain such as go daddy. I tried to use a self signed certificate but I am not able to redirect the website to https. Even though I added reverse proxy in my nginx.conf file to listen to port 80 and 443. Has anyone worked on this before and I will share more details on the same. i have this in my app.conf file server { listen 80; server_name appliication.com www.application.com Ip address 0.0.0.0; location /.well-known/acme-challenge/ { root /var/www/certbot; } location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; server_name appliication.com www.appliication.com Ip address 0.0.0.0; ssl_certificate /etc/path to key; #.crt ssl_certificate_key /etc/path to key; #.pem location / { proxy_pass http://backend:8000; #for demo purposes } } in my docker-compose.yml file I have the below code services: nginx: image: nginx ports: - "80:80" - "443:443" volumes: - ./app.conf:/etc/nginx/conf.d/default.conf - /path/to/your/certificate.pem:/etc/ssl/certs/your_certificate.pem - /path/to/your/private.key:/etc/ssl/private/your_private.key i am not sure where I am going wrong. can anyone help with this -
Django with crisp_forms and django_filters
I want to build a form to create a database object instance using the crispy Layout object. I need a Django filter which appears between the 2 radios (Article List and Category List) and the categories listboxes (see mock below). The 2 filters (Name and Level) should filter the available categories. So, I need a GET form (for the filters) inside the POST form (to create the database object). Any idea how to solve this with crispy? Thanks! -
Execute raw SQL before each select for specific model
I have a complicated report in Django, which is written as raw SQL, and than stored in the database as a database view. I have a Django model (managed=False), tied to that database view, so that I can utilize the django ORM and django rest framework, on top of the database view. This practice is something that I have used on several projects, and works fine. For one specific report, I found that I need to meddle with the postgres query planner, to get it running faster. Before each SELECT statement on that model (database view), to get the SQL to run faster, I need to do: SET enable_nestloop TO off; The query is quite complex, with aggregate functions, and joins on subqueries, so I gave up on trying to optimize it. Turning off the nestloop solves all my performance issues, and I am fine with that, as long as I turn it on back after the query. Here is an explanation of the problem and the solution. (What are the pitfalls of setting enable_nestloop to OFF) At the moment, what I do, is wrap the Report query in a database trasaction, and set the enable_nestloop only within that transaction, … -
Unable to send messages via React frontend and POST requests fail on Django REST API panel
I am building a chat application using React for the frontend and Django for the backend. I am facing the following two issues: Issue with sending messages in React: When I try to send a message through the React app, I receive a 400 Bad Request error. The API request is made to the backend using a POST request, but the response indicates that there was a problem. The error message doesn't provide much insight, and I cannot send the message. Issue with POST request in Django REST API panel: When I try to make a POST request from the Django REST framework interface (admin panel) to send a chat message, the request seems to go through successfully but redirects to a blank page (without an error). The data is not posted, and nothing changes on the frontend. However, when I use curl to send the same request, it works fine. Here’s a snippet of the relevant React code for sending messages: const handleSendMessage = async () => { if (message.trim() || file) { setSendingMessage(true); const formData = new FormData(); formData.append('receiver', selectedContact.id); formData.append('content', message); if (file) formData.append('file', file); try { const response = await fetch(`http://127.0.0.1:8000/api/chat/${userData?.current_basic_user?.username}/`, { method: 'POST', headers: { … -
Django Docker Setup: OperationalError - "FATAL: database 'guardian_grid' does not exist" with PostgreSQL After Running for a Few Days
I’m experiencing a recurring issue with my Django project configured to run with PostgreSQL in Docker. After a few days of smooth operation, the PostgreSQL database unexpectedly fails, and I receive the following error: django.db.utils.OperationalError: connection to server at "postgres" (172.18.0.2), port 5432 failed: FATAL: database "guardian_grid" does not exist I’ve shared my Docker Compose configuration below. The setup includes volumes for persistent data and backup storage for PostgreSQL. Despite this, the database sometimes "disappears," and I’m unsure why this is happening. I’m looking for insights into potential causes and solutions to ensure the database remains intact. volumes: guardian_grid_local_postgres_data: {} guardian_grid_local_postgres_data_backups: {} services: postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: guardian_grid_local_postgres container_name: guardian_grid_local_postgres volumes: - guardian_grid_local_postgres_data:/var/lib/postgresql/data - guardian_grid_local_postgres_data_backups:/backups - /home/ehabsami/Desktop/guardian_grid/init.sql:/docker-entrypoint-initdb.d/init.sql env_file: - .envs/.local/.postgres ports: - "5432:5432" healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 10s retries: 5 guardian_grid: build: context: . dockerfile: ./compose/production/django/Dockerfile # Ensure correct path for Django Dockerfile restart: always image: guardian_grid_local_django container_name: guardian_grid_local_django depends_on: postgres: condition: service_healthy redis: condition: service_started volumes: - .:/app:z command: /bin/sh -c "/run.sh" # Ensure run.sh exists ports: - "8000:8000" env_file: - .envs/.local/.django redis: image: "redis:alpine" ports: - "6379:6379" # Python and dependencies setup FROM docker.io/python:3.12.4-slim-bookworm AS python # Python build stage FROM python …