Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django FileField - how to save files to different directories
I have two similar forms for upload files, but I want to save files in different directories depending on the form. Let me explain, for example: if User uploaded file from Form_1 -> file should be save in media/folder_file_1/file.csv if User uploaded file from Form_2 -> file should be save in media/folder_file_2/file.csv Regarding models.py, forms.py, views.py, urls.py I just used examples from Django docs. index.html: <!DOCTYPE html> {% load static %} <body> <div class="page_secondblock secondblock"> <div class="secondblock__container _container"> <h1 class="secondblock__title"> The file you want to update: </h1> <h2 class="secondblock__title"> The file from which you want to get information: </h2> </div> </div> <div class="page_thirdblock thirdblock"> <div class="thirdblock__container _container"> <form method="POST" enctype="multipart/form-data" class="upload1" id="upload_container"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> <form method="POST" enctype="multipart/form-data" class="upload2" id="upload_container"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> </div> </div> </body> models.py: from django.db import models class UploadFile(models.Model): file = models.FileField(upload_to='working/') forms.py: from django import forms from .models import UploadFile class UploadFileForm(forms.ModelForm): class Meta: model = UploadFile fields = ['file'] views.py: from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .forms import UploadFileForm def index(request): return render(request, "index.html") def tools(request): return render(request, "index.html") def login(request): return render(request, "index.html") def upload_file(request): if request.method == 'POST': … -
How to configure SSL certificate inside my docker container?
I have a django application that running inside a docker container. However, while the application works perfectly fine inside my local PC when running inside the container it is unable to make any requests such as calling certain APIs or even pip install. All of these actions will throw an error like [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992). Only way I got pip install working is to do RUN pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host=files.pythonhosted.org --no-cache-dir -r requirements.txt Solutions tried: Copying my local rootCA.pem file to /usr/local/share/ca-certificates/ in the container RUN update-ca-certification Tried different python providers (alpine, buster, slim-buster) There are many more I couldn't remember I don't want to just turn verify off as it is bad practice so I'm trying to keep verification on. I have included my Dockerfile below. Dockerfile: FROM python:3.11.2-slim-buster ENV PYTHONUNBUFFERED=1 WORKDIR /app RUN apt-get update && apt-get install -y ca-certificates COPY certs/rootCA.pem /usr/local/share/ca-certificates/ RUN update-ca-certificates COPY requirements.txt requirements.txt RUN pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host=files.pythonhosted.org --no-cache-dir -r requirements.txt COPY . . CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] -
GET request to ListAPIView doesn't recognize query parameter in Django Rest Framework test case
I am encountering an issue with my Django Rest Framework test case where a GET request to a ListAPIView doesn't seem to recognize a query parameter. The same request works correctly when sent through Postman, but fails when executed within the test case. Here's an overview of the problem: I have a ListAPIView that represents a collection of model instances. The view works fine when tested manually through Postman, and it expects a query parameter called 'project' to filter the collection based on a specific project. However, when I try to send a GET request to the same ListAPIView within my test case, the query parameter 'project' is not recognized, resulting in an error response indicating that the project field is required. Here's a simplified version of the relevant code in my test case: class ShiftListTests(APITestCase): def setUp(self): self.user = User.objects.create_user(username='testuser', password='testpassword') self.client.force_authenticate(user=self.user) self.project = Project.objects.create(owner=self.user, task='Test Task', technical_requirement='Test Requirement', start='2023-05-01', hourly_rate=10.0) self.shift1 = Shift.objects.create(project=self.project, start_time=timezone.make_aware(timezone.datetime(2023, 5, 1, 9, 0, 0)), end_time=timezone.make_aware(timezone.datetime(2023, 5, 1, 17, 0, 0))) self.shift2 = Shift.objects.create(project=self.project, start_time=timezone.make_aware(timezone.datetime(2023, 5, 2, 9, 0, 0)), end_time=timezone.make_aware(timezone.datetime(2023, 5, 2, 17, 0, 0))) def test_get_shift_list(self): url = reverse('shift list') payload = {'project': self.project.id} response = self.client.get(url, data=payload, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) # … -
Django admin upload Image not serving in Html page
i am creating page which serves django admin upload images in page.. ---- this is my file structure in AWS EC2: enter image description here ------ this is what i got when try to find URL of image enter image description here --- This is collectstatic output: enter image description here i think -- i am not able to find the mistake i have done this is the output of the page: the images are not loading into AWS ec2 webpage Please help me out about this issue. as i mentioned above.. i tried max suggestions in stack-overflow and other references too.. i am expecting to serve images in html page which are in the path and not in the html page. ---- this is the inspect element screenshot of page. enter image description here ---- this is database image location : enter image description here please help. -
独自ドメインをEC2インスタンスのpublic IPに紐付けたが、そのドメインにブラウザからアクセスできない
実現したいこと: EC2インスタンスのpublic IPアドレスに紐づけた独自ドメイン(= example.com)にアクセスし、GunicornでサーブされているDjangoアプリからの応答を、Nginx as a reverse proxyを通じて、ブラウザに表示したいです。 問題点: public IPアドレスにアクセスすると、Djangoアプリからの応答を確認できます。 example.comにアクセスすると、「このサイトにアクセスできません」となります。 以上より、ドメインの紐付けに失敗していると予測するも、「example.com/admin」にはアクセスできるため、紐付け自体には問題がなさそうです。 やってきたこと: 1, Route53にて独自ドメインとEC2インスタンスのpublic IPを、Aレコード及びネームサーバーの設定を通じて、紐づけました。 2, HTTPアクセスを受けられるように、セキュリティグループでポート80を開け、ソースを0.0.0.0と設定した。 3, EC2インスタンス内で、Gunicorn/Django、Nginx、PostgreSQLのコンテナたちを、以下のdocker-compose.yml & default.confを用いて作成しました。 version: "3.9" services: web: # コンテナ名をwebに指定 container_name: web # NginxのDockerfileをビルドする build: # ビルドコンテキストはカレントディレクトリ context: . dockerfile: ./nginx/Dockerfile # ボリュームを指定 # ローカルの/staticをコンテナの/staticにマウントする volumes: - ./static:/static - ./nginx/conf.d:/etc/nginx/conf.d - ./etc/letsencrypt:/etc/letsencrypt - ./var/www/html:/var/www/html ports: - "80:80" depends_on: - api certbot: # 後のHTTPS化に使います image: certbot/certbot:v1.7.0 volumes: - /etc/letsencrypt:/etc/letsencrypt - /var/www/html:/var/www/html command: ["--version"] api: build: ./api command: gunicorn server.wsgi:application --bind 0.0.0.0:8000 environment: - OPENAI_API_KEY=${OPENAI_API_KEY} - SECRET_KEY=${SECRET_KEY} - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} - DB_HOST=${DB_HOST} - DB_PORT=${DB_PORT} volumes: - ./api:/app ports: - "8000" depends_on: - db db: image: postgres:13 environment: POSTGRES_DB: ${DB_NAME} POSTGRES_USER: ${DB_USER} POSTGRES_PASSWORD: ${DB_PASS} volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: upstream django { # サーバにDjangoのコンテナ名を指定。今回はapp # ポートはDjangoのコンテナの8000番ポート server api:8000; } server { # HTTPの80番ポートを指定 listen 80; server_name example.com; # プロキシ設定 # 実際はNginxのコンテナにアクセスしてるのをDjangoにアクセスしてるかのようにみせる location / { proxy_pass http://django; } } どうかアドバイス宜しくお願いいたします! -
object has no attribute 'META' when filtering Query in Django
It's my first time encountered this problem, the error says 'TevList' object has no attribute 'META' I tried putting .first() after filter but the error retains views.py @csrf_exempt def tevemployee(request): tev_id = request.POST.get('tev_id') qs_list = TevList.objects.filter(id=tev_id).first() return JsonResponse({'data': list(qs_list)}) ajax $('.item-details').click(function (event) { let id = $(this).attr("id"); $.ajax({ type: "POST", url: "{% url 'tev-employee' %}", data:{ tev_id : id } }).done(function(data){ }); models.py class TevList(models.Model): employee_name = models.CharField(max_length=128,blank=True, null=True) original_amount = models.FloatField(null=True, blank=True, default=0) status = models.CharField(default="On-going",max_length=128,blank=True, null=True) incoming_remarks = models.CharField(max_length=255, blank=True, null=True) correctness_remarks = models.CharField(max_length=255, blank=True, null=True) date_in = models.DateTimeField(default=datetime.now,blank=True, null=True) date_out = models.DateTimeField(blank=True, null=True) deleted_at = models.DateTimeField(blank=True, null=True) user_id = models.BigIntegerField(blank=True, null=True) class Meta: managed = True db_table = 'tev_list' -
DJANGO: database dependent combobox remains empty. No items appear
I would like to create a combobox and display data from a database table (names of cities) inside it. The page is app1/home.html. I created the files and migrated the database, but the combobox remains empty. I don't know what I did wrong. I'm new to Django, sorry. I have read many tutorials and questions, but I have not solved. How can I create the combobox and display City_Name in it? models.py from django.db import models class Select_City(models.Model): Select_City= models.IntegerField() def __str__(self): return self.Select_City forms.py from .models import Select_City class TestForm(forms.Form): some_input = forms.CharField(max_length=100) city = forms.ModelChoiceField(queryset=Select_City.objects.all()) class Meta: model = Select_City fields = ('City_Name',) views.py def combobox(request): query_results = Select_City.objects.all() if request.method =="POST": form = TestForm(request.POST) context = {'form': form, 'query_results': query_results} return render(request, 'app1/home.html', context) home.html <form method="post" novalidate> {% csrf_token %} <select id="sel_city" name="cities"> <option value="{{ query_results }}">Select</option> {% for item in query_results %} {% endfor %} </select> </form> -
AP Scheduler skips logging of the job execution - How to resolve?
This is how my scheduler configuration and the registered job looks like ` from django.core.management import call_command def start(): from django_apscheduler.jobstores import register_events, DjangoJobStore, register_job from apscheduler.schedulers.background import BackgroundScheduler scheduler = BackgroundScheduler() scheduler.add_jobstore(DjangoJobStore(), 'djangojobstore') print("Idhar aagya mein") try: @register_job(scheduler, 'interval', minutes=1, name="daily_bakcup", misfire_grace_time = 300, max_instances=3) def backup(): call_command('DB_Backup') except Exception as e: print("Error" , e) register_events(scheduler) scheduler.start() ` Here is the explanation on what the job does and where the error come. So, the job is to take backup of the database using Django's python manage.py dumpdata > file.json command, then upload it to Azure container. The thing I wanted to achieve is to perform the job and log the execution in the Job Execution tables (which is expected to happen implicitly when jobstores are used.) in the Database. Hence, it performs the job but doesn't log the execution in the tables, instead i get the below in the console. Job 'user_accounts.backup.backup' no longer exists! Skipping logging of job execution... Any suggestions and solution would help a lot. Thanks! -
There is an error of page not found ;Request method get method
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin/signup Raised by: django.contrib.admin.sites.catch_all_view You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I tried on stackoverflow but it gives me the post method to solve the error -
In Django, after creating models.py, how to create a combobox and populate me with database?
In the app1/home.html page, i would like to create a combobox and display data from a database table (city names) inside. A simple combobox with city names. I created the models.py file and migrated the database. How can I create the combobox and display City_Name in it? Thank you models.py from django.db import models class Select_City(models.Model): City_Name= models.IntegerField() def __str__(self): return self.City_Name -
Azure App Service web app: Django + Microsoft login redirect HTTPS issue
Azure App registration web redirect URL (it's HTTPS) as below: Using Azure App Service deployed the Django web app successfully: the above deploying result shows http://, but in Azure web app web it shows https://, also could open the web app using https successfully with valid as below: But when the web app redirected to Microsoft site to login, it uses http:// again which doesn't match the https:// configured in App registration: The MS authentication and redirection is handled by package ms_identity_web, code provided from https://github.com/Azure-Samples/ms-identity-python-django-tutorial/tree/main/1-Authentication/sign-in In development environment there is no issue since I use http://localhost:8000/auth/redirect as web redirect url in App registration. My issue could be the same as this one: link, but it covered the URL details so not sure if it was the same http/https mismatching issue. -
postgresql ERROR: duplicate key value violates unique constraint "django_apscheduler_djangojob_pkey"
(https://i.stack.imgur.com/rPvSI.png) when i build django(+django-apscheduler),postgresql,nginx i got error above this. django=4.2.2 python=3.8.10 postgresql=14.5 django-apscheduler=0.6.2 apscheduler=3.10.1 so i try to solve this error, search on google : modify postgres db : because "django_apscheduler_djangojob_id_seq" doesnt exist, so i created table("django_apscheduler_djangojobexecution_id_seq" is exist) CREATE SEQUENCE django_apscheduler_djangojob_id_seq INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START 1 CACHE 1 NO CYCLE; CREATE SEQUENCE SELECT setval('django_apscheduler_djangojob_id_seq',(SELECT MAX(id) FROM django_apscheduler_djangojob)); But it doenst work... comment out "Djangojobstore" : it works but i want to use djangojobstore in my operator.py : logger = logging.getLogger(__name__) def delete_dormant_user(): dormant_user = User.objects.filter(is_active=False) dormant_user.delete() @util.close_old_connections def delete_old_job_executions(max_age=604_800): DjangoJobExecution.objects.delete_old_job_executions(max_age) class Command(BaseCommand): help = "Runs delete_dormant_user." def start(self, *args, **options): scheduler = BackgroundScheduler( timezone=settings.TIME_ZONE ) #scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job( delete_dormant_user, trigger=CronTrigger(minute="*/3"), id="delete_dormant_user", max_instances=1, replace_existing=True, ) logger.info("Added job 'delete_dormant_user'.") scheduler.add_job( update_ingredient_links, trigger=CronTrigger(day_of_week="0-6", hour="04", minute="00"), id="update_ingredient_links", max_instances=1, replace_existing=True, ) logger.info("Added job 'update_ingredient_links'.") scheduler.add_job( delete_old_job_executions, trigger=CronTrigger( day_of_week="mon", hour="05", minute="00" ), id="delete_old_job_executions", max_instances=1, replace_existing=True, ) logger.info("Added weekly job: 'delete_old_job_executions'.") try: logger.info("Starting scheduler...") scheduler.start() except KeyboardInterrupt: logger.info("Stopping scheduler...") scheduler.shutdown() logger.info("Scheduler shut down successfully!") in my apps.py : class UsersConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "users" def ready(self): if settings.SCHEDULER_DEFAULT: from .operator import Command Command.start(self) please give me some wisdoms!! ps. since Mar 6 2022, django-apscheduler hasn't been updated... it can … -
Not recognizing components when using django-split-settings
Never used this app; first time using it. I have a problem with recognizing the components from one of my settings files. Here is my directory structure: survey/settings/ ├── components │ ├── common.py │ ├── directory_manipulation.py │ ├── django_allauth.py │ ├── django_crispy_forms.py │ ├── django_tailwind.py │ └── __init__.py ├── enviroments │ └── __init__.py ├── __init__.py └── __pycache__ └── __init__.cpython-311.pyc Here is my settings/__init__.py file: """ This is a django-split-settings main file. For more information read this: https://github.com/sobolevn/django-split-settings Default environment is `developement`. To change settings file: `DJANGO_ENV=production python manage.py runserver` """ from split_settings.tools import optional, include base_settings = [ # You can even use glob: 'components/*.py' ] # Include settings: include(*base_settings) Here is my settings/django_allauth.py AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] from components.base import INSTALLED_APPS INSTALLED_APPS += ( 'allauth', 'allauth.account', 'allauth.socialaccount', 'django.contrib.sites', ) SITE_ID = 1 Here is my settings/common.py """ Django settings for survey project. Generated by 'django-admin startproject' using Django 4.1.9. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path # Build … -
Django : DoesNotExist Error raised in post_signal handler
Trying to delete a Task instance with its subtasks, I encounter DoesNotExist: Task matching query does not exist. The following is the error message: Traceback (most recent call last): File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/fields/related_descriptors.py", line 218, in __get__ rel_obj = self.field.get_cached_value(instance) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/fields/mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^ KeyError: 'supertask' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/crackers/views.py", line 73, in delete print(task.delete()) ^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/base.py", line 1132, in delete return collector.delete() ^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/deletion.py", line 512, in delete signals.post_delete.send( File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/dispatch/dispatcher.py", line 176, in send return [ ^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/dispatch/dispatcher.py", line 177, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/crackers/signals.py", line 10, in reassess_achievement if instance.supertask is not None and instance.supertask.completed == False: ^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/fields/related_descriptors.py", line 236, in __get__ rel_obj = self.get_object(instance) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/fields/related_descriptors.py", line 199, in get_object return qs.get(self.field.get_reverse_related_filter(instance)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/query.py", line 637, in get raise self.model.DoesNotExist( crackers.models.Task.DoesNotExist: Task matching query does not exist. So far, I have figured out that the error is related to signal handler, since the same error does not … -
django channels app is blocking when handle many requests
i have a DRF project, using django channels, i have a endpoint that handles thousands requests for each 5seconds, sometimes this endpoint is blocking my app, what would be the best way to handle it? some posts adivises to use raise StopComsumer() in the disconect method, but not resolve this is my consumer class ChargerSessionConsumer(AsyncJsonWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.client_id = None self.group_name = None async def connect(self): self.group_name = 'room' self.client_id = self.scope["url_route"]["kwargs"]["client_id"] await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.channel_layer.group_add( self.client_id, self.channel_name ) await self.accept() async def websocket_disconnect(self, message): await self.channel_layer.group_discard( self.group_name, self.channel_name ) await self.channel_layer.group_discard( self.client_id, self.channel_name ) raise StopConsumer() -
Add Django super user token in http request
I use Django (as backend and frontend) for a website. I want to create http request with the condition (of use) to be Django super user. But I don't know how to add in the headers the token (or the proof that the user that uses the request is a super user). I tried this with the csrf token : First I use the {% csrf_token %} in the template. <form action="#" id="admin-add-event" method="POST"> {% csrf_token %} ... <button type="submit" id="admin-submit">Add event</button> </form> const url = `${window.BASE_URL}events/`; const form = document.getElementById('admin-add-event'); const data = { ... } let xhr = new XMLHttpRequest(); xhr.open('POST', url , true); xhr.setRequestHeader('X-CSRFToken', form.elements.csrfmiddlewaretoken.value); xhr.setRequestHeader("Content-Type", "application/json"); xhr.onload = function () { ... } xhr.send(JSON.stringify(data)); And in the Django view of the endpoint : @api_view(['GET', 'POST']) def all_events(request): if request.method == 'POST': if not request.user.is_superuser: return Response(status=status.HTTP_401_UNAUTHORIZED) # etc ... But the check of super user fails always I precise that I don't want to implemente a user system. I want to use the system of super user of Django. Thanks in advance ! -
How to use Django ImageField to upload to Google Cloud Storage instead of local
I want to use Django's ImageField on a model so people can upload a logo. I found the ImageField however reading from the docs it says Django stores files locally, using the MEDIAROOT***andMEDIAURL** settings.py I'm wondering how I can change the *upload_to= behavior to upload to a gcp bucket instead? If it's possible when I call .save what is saved to the database, the gcp bucket url? From reading the docs it doesn't say one way or the other if this is possible or if all images should be stored locally where the service is being ran. I have thought of saving the binary images directly to the db but that seems inefficient. -
How to add prefix before token in request using drf-yasg or drf-spectacular
I need add prefix "Token" before token in request header when using drf-yasg or drf-spectacular to create django drf API doc. I have tried multiple tests: Middleware: SWAGGER_SETTINGS 3)SPECTACULAR_SETTINGS: Token plus token in authorize form: Url configs: Options 1), 2) and 3) the request headers are: and with 4) return 401 http status code with the options 1), 2), 3) I receive 401 ""Authentication credentials were not provided." and with 4) invalid token Can you help me please? -
Django reverse() behind proxy
My Django REST API is deployed behind an API Gateway (Kong). I want to reserve() some urls in my APIViews. I would like to ask for help to get the right url format. Based on basepath of the API gateway. Communication flow: Client (requesting basepath) <-> Kong (forwarding to upstream) <-> Apache (Reverse Proxy) <-> Django Kong defines a basepath and an upstream to forward client request to Django. Kong includes X_FORWARDED_HOST and X_FORWARDED_PATH in the HTTP header. X_FORWARDED_PATH contains the basepath of the gateway. X_FORWARDED_HOST contains the gateway-url. Gateway basepath is: /gateway-basepath Upstream path is: mydomain.com/py/api/v1 Basically, without gateway, Django reverse() creates following url for users endpoint: mydomain.com/py/api/v1/users/ With the API gateway, the Django creates follow path: apigatewayurl.com/gateway-basepath/py/api/v1/users/ Django is considering X_FORWARDED_HOST, but not X_FORWARDED_PATH I need following result: apigatewayurl.com/gateway-basepath/users Otherwise the Django url resolving is not usable within the api gateway. I would appreciate any help. urls.py from rest_framework.views import APIView from rest_framework import routers from . import views class APIRootView(APIView): def get(self, request, format=None): return Response({ 'users': reverse('user-list', request=request, format=format), }) router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) urlpatterns = [ path('api/v1/', APIRootView.as_view(), name="api_root"), ] urlpatterns += router.urls views.py from rest_framework import viewsets from django.contrib.auth import models as django_models … -
Django 404 email notification
I want to get an email every time someone on my site gets a 404. I added the following code to my settings.py file DEBUG = False MANAGERS = ADMINS MIDDLEWARE = [ 'django.middleware.common.BrokenLinkEmailsMiddleware', ] The problem is that it just doesn't work. After reading this ticket I decided to try to following I went to the file django/middleware/common.py And made a change to the following class class BrokenLinkEmailsMiddleware(MiddlewareMixin): def process_response(self, request, response): """Send broken link emails for relevant 404 NOT FOUND responses.""" if response.status_code == 404 and not settings.DEBUG: domain = request.get_host() path = request.get_full_path() referer = request.META.get("HTTP_REFERER", "") if not self.is_ignorable_request(request, path, domain, referer): ua = request.META.get("HTTP_USER_AGENT", "<none>") ip = request.META.get("REMOTE_ADDR", "<none>") mail_managers( "Broken %slink on %s" % ( ( "INTERNAL " if self.is_internal_request(domain, referer) else "" ), domain, ), "Referrer: %s\nRequested URL: %s\nUser agent: %s\n" "IP address: %s\n" % (referer, path, ua, ip), fail_silently=True, ) return response FROM referer = request.META.get("HTTP_REFERER", "") To referer = request.META.get("HTTP_REFERER", "None") New class class BrokenLinkEmailsMiddleware(MiddlewareMixin): def process_response(self, request, response): """Send broken link emails for relevant 404 NOT FOUND responses.""" if response.status_code == 404 and not settings.DEBUG: domain = request.get_host() path = request.get_full_path() referer = request.META.get("HTTP_REFERER", "None") if not self.is_ignorable_request(request, path, domain, … -
Getting a problem after deploy a Django app on Render
I developed an app in Django using PostgreSQL as DataBase, on a local environment it works without problems, but when it was deployed on Render.com it the app throws me this error. I had to set the debug in True to watch the error This is that Render console shows me: django.db.utils.ProgrammingError: relation "management_notificacion" does not exist Jun 28 04:55:41 PM LINE 1: SELECT COUNT(*) AS "__count" FROM "management_notificacion" ... This is the line of code that is given the error, but in local works without problems context_processors.py from management.models import * def get_notificaciones(request): notificaciones = Notificacion.objects.filter(receptor=request.user.id)[:3] no_vistas = Notificacion.objects.filter(receptor=request.user.id, visto=False).count() return { 'notificaciones': notificaciones, 'no_vistas': no_vistas } def get_mensajes(request): mensajes = Mensaje.objects.filter(receptor=request.user.id)[:4] no_vistos = Mensaje.objects.filter(receptor=request.user.id, visto=False).count() return { 'mensajes': mensajes, 'no_vistos': no_vistos } If anyone can give a hint to solve this, I'll be so grateful! -
How can I modify attributes of objects in a Django queryset for data presentation without modifying the original object?
I want to present a list of objects for which I want to filter/modify one attribute during the presentation of the data. Something close to an annotation, but I did not manage to do it with annotations. These are the models class Airline (models.Model): name = models.CharField() destinations = models.ManyToManyField("city") customers = models.ManyToManyField("user") class City (models.Model): name = models.CharField() country = models.CharField() class User (models.Model): name = models.CharField() preferredDestinations = models.ManyToManyField("city") I want, for a given user, present a list of the Airlines the user is customer, and for each Airline present the list of destinations for the Airline. But instead of presenting all the airline destinations I only want to present the destinations preferred by the user. e,g, Airline1.destinations=["New York", "London", "Paris", "Madrid] Airline2.destinations=["Madrid", "Barcelona", "Rome", "Berlin", "London"] User1.preferredDestinations=["Madrid", "Barcelona", "Paris"] With user1 being a customer of Airline1 and Airline 2, I want the page to present a table showing to which of the user preferred destination every airline flies to. I.e. I do not want to see all the destinations the airline flies to, only the ones the user is interested: E.g. Welcome User1! These are your airlines that fly to your preferred destinations Airline | Destination | … -
DJANGO: replace a combobox created successfully in a list of views.py, with one created with classes in forms.py?
I'm new to Django. I saw that there are 2 different ways to create comboboxes and forms. I would like to replace my current mode, already successfully created, with another mode. WAY 1 (works well, correctly): I have a combobox that works fine, created by putting the items in a list in views.py, for example: color_choices = ("Red","Blue","Black", "Orange"). I am currently using this mode. WAY 2: Way 1 works fine correctly for me, but only now I've seen that it's possible to create comboboxes also by creating a forms.py file, importing from django import forms, and then writing the items in the classes. The combobox uses a static list QUESTION: How can I modify my code (which uses Way 1) and replace it with forms.py with Way 2 classes? I would like to use the classes and the forms.py file, and I would not like to use the items in the views.py file (it works correctly fine with Way 1). Can you show me how I can use Way 2 correctly? Thank you all! Which of the two ways is more correct and better in terms of loading speed? Thank you all! P.S: comboboxes are database independent. they don't … -
Google Analytics GA4
The number of users who have registered on my website on GA4 is less than the one I got from the DB. Anyone can help here? Both google analytics and extracted data are in the UTC time and on GA4 Im checking the total users value Thannk you! -
Django xhtml2pdf, changing to custom font not working
I'm trying to change the font in my html to pdf project using xhtml2pdf (version 0.2.11) in Django (version 4.2.2). I'm running the project on my Windows 11 Home 22H2, using python 3.11.0 Here is how I try to import the font file html snippet, but the font did not reflect on the page. html snippet @font-face { font-family: Ysabeau Infant; src: url('fonts/Ysabeau-Infant.ttf'); } Views.py def report_rednder_pdf_view(request, *args, **kwargs): pk = kwargs.get('pk') report = get_object_or_404(Report, pk=pk) template_path = 'reports/pdf2.html' context = {'report': report} # Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') # If downloadable remove comment #response['Content-Disposition'] = 'attachment; filename="report.pdf"' # If viewable remove comment response['Content-Disposition'] = 'filename="report.pdf"' # find the template and render it. template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF( html, dest=response) # if error then show some funny view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response I tried using the absolute path C:\Users\USER\Desktop\PROJECT\static\fonts\Ysabeau-Infant.ttf instead of the relative path, but that did not work, I get the error: TTFError Exception Value: Can't open file "C:\Users\USER\AppData\Local\Temp\tmpwsd3c9z2.ttf" and from the terminal I get the error, Permission denied: 'C:\Users\USER\AppData\Local\Temp\tmpwsd3c9z2.ttf' I tried running …