Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to handel default Django authentication in forntend
I'm working on a project, in the back-end we are using Django with Rest and for front we are using Wordpress and we want to send otp for user and if the OTP code from user is valid then login the user and save the CSRF-token and so on .. but here is my problem I didn't wanted to save the opt in a table and in chatgpt it suggested that I can save it in session or memory cash, I wanted to try the session way but I encounter a problem : after calling the /send_otp/ and getting the otp I need to call the /login/ and check if the otp is a mach, but in login it returns the otp from session None and I can access the session I saved in the send_otp this is the two functions send_otp and login : class SendOTPView(APIView): def post(self, request): serializer = OTPSerializer(data=request.data) if serializer.is_valid(): phone_number = serializer.validated_data["phone"] otp_code = randint(100000, 999999) request.session['otp_code'] = otp_code print("otp in sendOTP",request.session.get("otp_code")) otp_send(phone_number, otp_code) return Response( {"detail": "OTP sent successfully"}, status=status.HTTP_200_OK ) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class UserLoginView(APIView): def post(self, request): serializer = UserLoginSerializer(data=request.data) if serializer.is_valid(): stored_otp = request.session.get("otp_code") print(stored_otp) user_entered_otp = serializer.validated_data["otp"] phone_number = … -
Cpanel Cron Job not working for everyday day
Cpanel Cron jobs Images I have 3 cron jobs in my cpanel, I am hitting APIs with curl, my hourly cron job is working fine but Daily cron job is not, monthly is not get to test yet for cron: you might think there is some error with API, so heres the deal: I edited the same API and changed its time to minute, the cron job starts working started wokring When i hit the API with postman manually it wokrs also i put the curl command that i put in cron into the live terminal of ssh, it works It is so weird but I am now irritated, Any Help? -
Django trying to encrypt fields when creating database and retrieveing them in decrypted form, how can I achieve this?
I am working on a django project where I need to store data inside some columns in an encrypted format and decrypt it on the fly whenever querying the said data. I have managed to encrypt the data while storing using cryptography-Fernet. def save(self, *args, **kwargs): if isinstance(self.first_name, str): self.first_name = cipher_suite.encrypt(self.first_name.encode()) super().save(*args, **kwargs) but When I am trying to retrieve the data, I am not able to fetch it in a decrypted format, As I do not know which method to override to achieve this result. What can I do to make this work? I have tried creating a property at django model But I am unable to trigger it, as I am not aware on how to trigger a model property in django models when a queryset is being executed. This is the property in question. @property def enc_first_name(self): if self.first_name: val = cipher_suite.decrypt(self.first_name).decode() return val return self.first_name Alternate solutions I tried, because our project is on python 3.10 and django 5.0, I am unable to use django-cryptography library which would have reduced complexity of this task tremendously. Also I have been recommended to use microsoft-presidio library but that only seems to work on text data directly. I … -
How to import a folder into postman?
Shows an error "No supported files found for import." I was trying to import my django folder into postman to test api's. Firstly I tried to do it in the postman app and then i installed postman extension from the vs code, the result was same. -
Django connect to remote Postgres: '127.0.0.1 works while 'localhost' fails
I set up local port forwarding to remote server on which a Postgres db is running. ssh -v -L 127.0.0.1:5433:localhost:5432 user@server-ip I can't connect from my django local server if host is set to localhost but it works if replaced by 127.0.0.1 My django settings: # settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '<db_name>', 'USER': '<db_user>', 'PASSWORD': 'django', 'HOST': 'localhost', 'PORT': '5433', } } When I run server, I got error as below: Error occurred during checks: OperationalError('connection failed: :1), port 5433 failed: could not receive data from server: Connection refused\ncould not send startup packet: Connection refused') I wanted to identify if the connection issue comes from client or server side, so I tried to connect to the db by psql: psql <db_name> -U <db_user> -p 5433 -h localhost and it works !!! So I guessed it was client issue. The django server could only connect to the db only when I changed 'HOST': 'localhost' to 'HOST': '127.0.0.1' My /etc/hosts: 127.0.0.1 localhost 255.255.255.255 broadcasthost ::1 localhost 127.0.0.1 postgres 127.0.0.1 mysql 127.0.0.1 redis pg_hba.conf: 127.0.0.1 localhost 255.255.255.255 broadcasthost ::1 localhost # Added by saritasa 127.0.0.1 postgres 127.0.0.1 mysql 127.0.0.1 redis # Added by Docker Desktop # To allow the … -
Issue accessing deeply nested attributes in Django Rest Framework serializer's validate method
I'm facing an issue while trying to access deeply nested attributes within the validate method of a Django Rest Framework serializer. Here's a simplified version of my serializer: from rest_framework import serializers from myapp.models import User class YourSerializer(serializers.ModelSerializer): def validate(self, attrs): if hasattr(self.parent.instance, 'vehicle'): if hasattr(self.parent.instance.vehicle, 'engine'): if hasattr(self.parent.instance.vehicle.engine, 'fuel'): fuel_type = self.parent.instance.vehicle.engine.fuel.diesel if fuel_type: pass else: raise serializers.ValidationError("Fuel type is not available.") else: raise serializers.ValidationError("Fuel attribute is not available.") else: raise serializers.ValidationError("Engine attribute is not available.") else: raise serializers.ValidationError("Vehicle attribute is not available.") return attrs In the validate method, I'm attempting to access deeply nested attributes (vehicle.engine.fuel.diesel) of the parent instance. The thing is Model engine is created after user does ABC operations, and same applies for fuel, and diesel. When a load of people work on codebase its tough to identify if a these Models are created or not, normally getattr() and hasattr() are used, but clubbing these a lot makes code look messy. Tried static loots like mypy and pylint, they help to a certain extent but sometimes, TypeError, NoneType issues popup. Not sure how to fix these. Thank you for your help! -
Django can't find leaflet admin widget.html
I want to use LeafletGeoAdmin in the Admin pages. from leaflet.admin import LeafletGeoAdmin @admin.register(Marker) class MarkerAdmin(LeafletGeoAdmin): list_display = ("name", "location") When I try to add a marker, I get the error: TemplateDoesNotExist at /admin/my_app/marker/add/ Exception Value: leaflet/admin/widget.html Django tried loading these templates, in this order: django.template.loaders.filesystem.Loader: /home/me/my_map/.venv/lib/python3.10/site-packages/django/forms/templates/leaflet/admin/widget.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/me/my_map/my_map/templates/leaflet/admin/widget.html (Source does not exist) ... etc ... So it's looking for widget.html in paths of the form <many-places>/leaflet/admin/widget.html. None of the places it's looking in has it. By looking in .venv I did find it at /home/me/my_map/.venv/lib/python3.10/site-packages/leaflet/templates/leaflet/admin/widget.html instead of at site-packages/django/forms/templates/, etc. So I added that templates/ location with both absolute and relative paths to settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'my_app','templates'), '/home/me/my_map/.venv/lib/python3.10/site-packages/leaflet/templates/', os.path.join(BASE_DIR,'.venv/lib/python3.10/site-packages/leaflet/templates/') ], ... But it still gives me the same error. why does django-leaflet not know the right path, and 2) why can't Django find it at the template path I specified? -
How can I serve React Frontend and Django Backend on IIS?
Background We have an application using React.js for the frontend and Django for the backend. We are attempting to deploy this application on an Azure virtual machine with IIS. Problems Encountered Backend Accessibility: We are uncertain whether our Django server is running and how to access it. Accessing localhost only serves the frontend, raising concerns about frontend-backend communication. 404 Error on Page Refresh: When navigating to authentication/sign-in from the frontend, it works fine. However, refreshing this page results in a HTTP Error 404.0 - Not Found error. It seems IIS is looking for a physical path that doesn't exist, as the build folder contains only static files (CSS, JS, etc.). Steps Taken Created a new instance on Azure: Installed Python and other necessary packages. Configured IIS: Enabled IIS features and other relevant features. Installed SSL certificate (.pfx) using MMC to enable HTTPS support. Moved project folder to C:\inetpub\wwwroot. Configured the Python path and FastCGI path in the web.config file, placed next to the project folder. Setup Virtual Directory: Moved the build folder (static build from React) to the virtual directory. Completed all configurations for mapping, FastCGI, and static file handling. Running the Application: The frontend is served successfully when accessed … -
Django User object has no attribute user
I am trying to create some custom authentication classes to check if the request user is part of certain groups or not. However, I am getting this AttributeError: 'User' object has no attribute 'user' appear and I dont know how to resolve it. This is the file I created for my custom authentication classes: from rest_framework import permissions class IsManager(permissions.BasePermission): def has_permission(self, request, view): if request.user.user.group.filter(name='managers').exists(): return True else: return False class IsDeliveryCrew(permissions.BasePermission): def has_permission(self, request, view): if request.user.user.group.filter(name='delivery crew').exists(): return True else: return False This is me view file: from rest_framework import generics, status from rest_framework.permissions import IsAuthenticated, IsAdminUser from rest_framework.response import Response from rest_framework.throttling import AnonRateThrottle, UserRateThrottle from django.shortcuts import get_object_or_404 from django.http import HttpResponseBadRequest from django.contrib.auth.models import Group, User from .models import Category, MenuItem, Cart, Order, OrderItem from .serializers import CategorySerialzier,MenuItemSerialzier,CartHelpSerializer, CartAddSerialzier,CartRemoveSerializer, CartSerialzier, ManagerListSerializer,OrderSerialzier,OrderItemSerializer,OrderAddSerializer, OrderItemHelperSerialzier from .permissions import IsManager, IsDeliveryCrew from datetime import date import math class CategoriesView(generics.ListCreateAPIView): throttle_classes=[UserRateThrottle,AnonRateThrottle] queryset = Category.objects.all() serializer_class = CategorySerialzier permission_classes= [IsAdminUser] class MenuItemsView(generics.ListCreateAPIView): throttle_classes=[UserRateThrottle,AnonRateThrottle] queryset = MenuItem.objects.all() serializer_class = MenuItemSerialzier search_fields = ['title','category__title'] ordering_fields = ['price','category'] def get_permissions(self): permission_classes = [] if self.request.method != 'GET': permission_classes = [IsAuthenticated,IsAdminUser] return [permission() for permission in permission_classes] class SingleMenuItemView(generics.RetrieveUpdateDestroyAPIView): throttle_classes=[UserRateThrottle,AnonRateThrottle] queryset = MenuItem.objects.all() serializer_class … -
Filtering row with same column date value
I have a datetime field, and I want to filter the rows that has the same date value. models.py class EntryMonitoring(models.Model): student = models.ForeignKey('Student', models.DO_NOTHING) clockin = models.DateTimeField() clockout = models.DateTimeField(null=True) views.py def check_attendance(request, nid): day = EntryMonitoring.objects.filter( clockout__isnull=False, '# same value', student=nid ).annotate(...) # do something I wanted to add inside that filter query that clockin__date has the same value as clockout__date. Is that possible? If it is, what would be the right query to filter it? -
How to move submit row to the top of the Django admin panel
I have pretty large list of objects so I would like to move the "save" button in the Django admin panel to the top of the list of objects, rather than the bottom. This would be similar to the result shown in the attached image. -
Issues with File Encryption/Decryption using pycryptodome
We've recently upgraded our project from Python 2.7 and Django 1.11 to Python 3.11 and Django 3.2. In the process, we've switched from using the pycrypto library to pycryptodome for cryptographic operations. Our Django application handles file uploads and downloads with encryption and decryption as follows: File Uploads: When a user uploads a file, it gets encrypted and stored in Google Cloud Storage (GCS) with a .enc extension. File Downloads: When a user requests to download a file, Django retrieves the file from GCS, decrypts it, and then sends the decrypted file to the user. Since the migration, we've encountered issues related to the encryption and decryption process. Specifically, the files are not being correctly encrypted or decrypted, leading to corrupted downloads. Here's a brief outline of our current approach: Encryption: Using pycryptodome to encrypt files before uploading to GCS. Decryption: Using pycryptodome to decrypt files after downloading from GCS. Has anyone else faced similar issues after upgrading to Python 3.11 and Django 3.2? Any insights or solutions to ensure proper encryption and decryption with pycryptodome in this setup would be greatly appreciated. Here' my crypto.py, which handles encryption and decryption from Crypto.Cipher import AES from Crypto import Random from … -
psycopg2.errors.UndefinedTable: relation "mydjangoapp_mymodel" does not exist
I am managing a django app built by third parts. I have configured in settings.py the connection to a new db 'default': { # changed 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'waterwatch', 'USER': 'waterwatch_main', 'PASSWORD': '****', 'HOST': 'localhost', } Now I want to populate the new database with the table in my models.py, that is class WaterConsumption(models.Model): Id = models.IntegerField(primary_key=True) Suburb = models.CharField(max_length=100) NoOfSingleResProp = models.IntegerField() AvgMonthlyKL = models.IntegerField() AvgMonthlyKLPredicted = models.IntegerField() PredictionAccuracy = models.IntegerField() Month = models.CharField(max_length=50) Year = models.IntegerField() DateTime = models.DateTimeField() geom = models.PointField() def __str__(self): return self.Suburb class Meta: verbose_name_plural = 'WaterConsumption' so I run python manage.py makemigrations but I get django.db.utils.ProgrammingError: relation "waterwatchapp_waterconsumption" does not exist well... I guess that is obvious, I am actually trying to create new tables in my new database. I guess something is wrong with the migrations. so I have dropped and recreated the database, deleted all files in waterwatchapp/migrations , except __init__.py waterwatchapp/__pycache__ waterwatch/__pycache__ But as I run again python manage.py makemigrations or python manage.py migrate, I still get the same error. Why does django does not creates the tables anew? It seems to me that django is still somehow following a sort of track of what was in the database before. … -
Unable to process the input data from ModelMultipleChoiceField in Django
I've been trying to process the data captured from a simple Django Model Form, and for some reason, it isn't possible to access the group of items selected under ModelMultipleChoiceField. I'm only able to access only one item from the selected items in the form. The Model: class Student(models.Model): name = models.CharField(max_length=80) subjects = models.ManyToManyField(Subject) house = models.ForeignKey(House, on_delete=models.CASCADE, related_name="students_of_house") The Model form: class AddStudentForm(forms.Form): name = forms.CharField(label="Full Name") house = ModelChoiceField(queryset=House.objects.all()) subjects = ModelMultipleChoiceField(queryset=Subject.objects.all()) The view function to process POST and create a Student Object.: def add_student(request): if request.method == "POST": name = request.POST["name"] house = House.objects.get(id=int(request.POST["house"])) subject_ids = request.POST["subjects"] new_student = Student(name=name, house=house) new_student.save() for sub_id in subject_ids: new_student.subjects.add(Subject.objects.get(id=int(sub_id)) new_student.save() return HttpResponseRedirect(reverse("administration:students")) context = { "add_student_form": AddStudentForm(), } return render(request, "administration/add_student.html", context) Now, I later tried using form = AddStudentForm(request.POST) and if form.is_valid(): route, which made it work successfully. But I'm having a hard time figuring out the reason why the above method isn't working. The code which worked: def add_student(request): if request.method == "POST": form = AddStudentForm(request.POST) if form.is_valid(): name = form.cleaned_data["name"] house = form.cleaned_data["house"] subject_ids = form.cleaned_data["subjects"] new_student = Student(name=name, house=house) new_student.save() for sub_id in subject_ids: new_student.subjects.add(Subject.objects.get(id=sub_id.id)) new_student.save() return HttpResponseRedirect(reverse("administration:students")) context = { "add_student_form": AddStudentForm(), } … -
Django Allauth headless Unauthorized 401 (Initial)
I'm receiving 401 when trying to reach the end point "/_allauth/browser/v1/auth/password/reset", althoug sending cookie, crsf and the key for email reseting. I'm following the flow of reseting the users password from a vuejs Frontend with this: async function sendEmailReset() { spin.value = true; try { const resp = await api.get("/api/email-reset/" + email.value); if (resp.data.status == "none") { error_message.value = "Este e-mail não existe no sistema. Faça o processo de registro novamente."; wrongCredentials.value = true; return; } else if (resp.data.status == "social") { error_message.value = "Este email foi cadastrado com uma conta social. Faça login com o Google."; wrongCredentials.value = true; return; } else { const response = await api.post( "/\_allauth/" + authClient + "/v1/auth/password/request", { email: email.value }, { headers: { "Content-Type": "application/json" }, } ); console.log(response); if (response.data.status == 200) { sentEmail.value = true; } else { error_message.value = "Ocorreu um erro ao enviar o e-mail. Verifique se o e-mail está correto."; wrongCredentials.value = true; } } } catch (error) { console.error(error); error_message.value = error.response?.data.detail || "Ocorreu um erro na conexão com o servidor. Se persistir, tente novamente mais tarde."; wrongCredentials.value = true; } finally { spin.value = false; email.value = ""; } } it works fine and send … -
Django custom admin template view problem
I changed the admin site index template in Django like this: admin.site.index_template = "admin/list-aprovals.html" but how can i send my model datas this page or can i add a custom view for this url: path('admin/', admin.site.urls), So, I want to work with the existing django admin, but I only want to change the template and see my models in this special template, but with the original admin app. Is this possible in Django? How do I solve this problem? I tried custom app but i want to use original contrib admin. -
How to add data to Django's database by the click of a button using JS
I'm trying to add this data on database when it's clicked. It updates on my website which is static. But the data in not updating on the Database. Showing list From database on index.html <ul id="myUL"> {% for name in names %} {% if name.com == True %} <li class="checked">{{name.names}}</li> {% else %} <li>{{name.names}}</li> {% endif %} {% endfor %} </ul> JavaScript code on index.html. I want to make it like if I click on the button then the the data will be added in the database. Then if i Refresh it The new task which I've implemented. It'll show. Also When the on of the item is checked it will be updated which is true or false. When I check one of the tasks it'll automatically update the database. // Add a "checked" symbol when clicking on a list item var list = document.querySelector('ul'); list.addEventListener('click', function(ev) { if (ev.target.tagName === 'LI') { ev.target.classList.toggle('checked'); } }, false); // Create a new list item when clicking on the "Add" button function newElement() { var li = document.createElement("li"); var inputValue = document.getElementById("myInput").value; var t = document.createTextNode(inputValue); li.appendChild(t); if (inputValue === '') { alert("You must write something!"); } else { document.getElementById("myUL").appendChild(li); } document.getElementById("myInput").value … -
Django Template Inheritance Issue: {% if %} Block Not Rendering When Extending base.html
Problem Description I'm working on a Django project where I have a form that, when submitted, calculates some results and displays them on the same page. The issue arises when I use a base template (base.html). Without using base.html, everything works perfectly, and the results are displayed correctly. However, when I extend from base.html, the content within the {% if results %}{% endif %} block in my test.html template doesn't get displayed at all. base.html Here is my base.html: <!DOCTYPE html> <html> <head> <title>{% block title %}AbiturTest{% endblock %}</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'main/css/style.css' %}"> <link rel="icon" type="image/x-icon" href="{% static 'main/img/icon.ico' %}"> <link rel="apple-touch-icon" href="{% static 'main/img/icon.png' %}"> <link rel="shortcut icon" href="{% static 'main/img/icon.ico' %}"> </head> <body> <header> <nav> <ul> <li><a href="{% url 'home' %}">Home</a></li> <li><a href="{% url 'test' %}">Test</a></li> </ul> </nav> </header> <div class="container"> {% block content %}{% endblock %} </div> </body> </html> test.html Here is my test.html: {% extends 'main/base.html' %} {% block title %}Test - AbiturTest{% endblock %} {% block content %} <h1>Тест AbiturTest</h1> <form id="test-form" method="post"> {% csrf_token %} <ul> {% for question in questions %} <li>{{ question.text }} <div class="radio-buttons"> <input type="radio" id="q{{ question.id }}_1" class="radio-button" name="answer_{{ question.id }}" value="1" … -
aws app running django static s3 url missing colon wrong url
this is my first post and i was to highlight a problenm that i've struggled with for a whole day. While configuring my django project by recovering the static files from an s3 bucket i've ended up with a problem, the url prefixed in fron of the static resources was generating without : after the protocol, like this: <link rel="shortcut icon" type="image/png" href="https//django-examplebucketname.s3.amazonaws.com/static/images/favicon.png"> so at the css, js and all the other static resources were giving 404. in the tamplate i had: {% load static %} and the settings file instead was configured like that: WS_ACCESS_KEY_ID = "myid" AWS_SECRET_ACCESS_KEY = "mykey" AWS_STORAGE_BUCKET_NAME = "django-examplebucketname" AWS_S3_REGION_NAME = "my-region" AWS_S3_CUSTOM_DOMAIN = "django-examplebucketname.s3.amazonaws.com" AWS_S3_URL_PROTOCOL = "https" AWS_S3_USE_SSL = True AWS_S3_VERIFY = True AWS_LOCATION = "static/" STATIC_URL = "https://django-examplebucketname.s3.amazonaws.com/static/" STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" but the static url was not taken in consideration and once released over apprunning the url was always missing the : (colon) after the protocol no other configurations were applied over the project. With the local setting and whitenoise was working. I've checked: the policy on the bucket --> they were ok (trying to connect directly to a resource via the bucket url was reachable) changing the static_url manually override the static … -
Pygame in django
I'm trying to make an online game using Django, but having some trouble: Here is my game code in py/main.py import pygame import sys def main(): pygame.init() screen = pygame.display.set_mode((50, 50)) pygame.display.set_caption("Test") while True: screen.fill((255, 255, 255)) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() pygame.display.update() When I run server, it said " no module name 'pygame' " After that, i tried to "py -m pip install pygame" but it said: already have enter image description here Then how can I import pygame in Django? -
How the PrivateFileField handles validators in django?
class AbstractFirmwareImage(TimeStampedEditableModel): build = models.ForeignKey(get_model_name('Build'), on_delete=models.CASCADE) file = PrivateFileField( 'File', upload_to=get_build_directory, max_file_size=app_settings.MAX_FILE_SIZE, storage=app_settings.PRIVATE_STORAGE_INSTANCE, max_length=255, validators=[MaxLengthValidator(255)], ) type = models.CharField( blank=True, max_length=128, choices=FIRMWARE_IMAGE_TYPE_CHOICES, help_text=_( 'firmware image type: model or ' 'architecture. Leave blank to attempt ' 'determining automatically' ), ) I want to increase the limit of file name length to 255 and it is implemented correctly that I know as I have checked it multiple times on my local serverand my server. But when I test it for a bigger filename, the tests pass without showing an error? Why is it so? def test_filename_within_limit(self, **kwargs): org = kwargs.pop('organization', self._get_org()) category = kwargs.pop('category', self._get_category(organization=org)) build1 = self._create_build(category=category, version='0.1') file = SimpleUploadedFile('a' * 74763, b'') image = self._create_firmware_image( build=build1, type=self.TPLINK_4300_IMAGE, file=file ) image.full_clean() def test_filename_exceeds_limit(self): file = SimpleUploadedFile('a' * 300, b'') image = FirmwareImage(file=file) with self.assertRaises(ValidationError): image.full_clean() def _create_build(self, **kwargs): opts = dict(version='0.1') opts.update(kwargs) category_opts = {} if 'organization' in opts: category_opts = {'organization': opts.pop('organization')} if 'category' not in opts: opts['category'] = self._get_category(**category_opts) b = Build(**opts) b.full_clean() b.save() return b def _create_firmware_image(self, **kwargs): opts = dict(type=self.TPLINK_4300_IMAGE) opts.update(kwargs) build_opts = {} if 'organization' in opts: build_opts['organization'] = opts.pop('organization') if 'build' not in opts: opts['build'] = self._get_build(**build_opts) if 'file' not in opts: opts['file'] = … -
Python 3.12 Sentry-sdk AttributeError: module 'collections' has no attribute 'MutableMapping'
I tried to use sentry-sdk latest version with Python 3.12, but when I run my django app, it shows me following error: AttributeError: module 'collections' has no attribute 'MutableMapping' Full trace as follows: File "/usr/local/lib/python3.12/site-packages/sentry_sdk/__init__.py", line 1, in <module> from sentry_sdk.hub import Hub, init File "/usr/local/lib/python3.12/site-packages/sentry_sdk/hub.py", line 5, in <module> from sentry_sdk.scope import Scope, _ScopeManager File "/usr/local/lib/python3.12/site-packages/sentry_sdk/scope.py", line 11, in <module> from sentry_sdk.attachments import Attachment File "/usr/local/lib/python3.12/site-packages/sentry_sdk/attachments.py", line 5, in <module> from sentry_sdk.envelope import Item, PayloadRef File "/usr/local/lib/python3.12/site-packages/sentry_sdk/envelope.py", line 6, in <module> from sentry_sdk.session import Session File "/usr/local/lib/python3.12/site-packages/sentry_sdk/session.py", line 5, in <module> from sentry_sdk.utils import format_timestamp File "/usr/local/lib/python3.12/site-packages/sentry_sdk/utils.py", line 1302, in <module> HAS_REAL_CONTEXTVARS, ContextVar = _get_contextvars() ^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/sentry_sdk/utils.py", line 1272, in _get_contextvars if not _is_contextvars_broken(): ^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/sentry_sdk/utils.py", line 1213, in _is_contextvars_broken from eventlet.patcher import is_monkey_patched # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/eventlet/__init__.py", line 6, in <module> from eventlet import convenience File "/usr/local/lib/python3.12/site-packages/eventlet/convenience.py", line 7, in <module> from eventlet.green import socket File "/usr/local/lib/python3.12/site-packages/eventlet/green/socket.py", line 21, in <module> from eventlet.support import greendns File "/usr/local/lib/python3.12/site-packages/eventlet/support/greendns.py", line 78, in <module> setattr(dns, pkg, import_patched('dns.' + pkg)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/eventlet/support/greendns.py", line 60, in import_patched return patcher.import_patched(module_name, **modules) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/eventlet/patcher.py", line 132, in import_patched return inject( ^^^^^^^ File "/usr/local/lib/python3.12/site-packages/eventlet/patcher.py", line 109, in inject module = … -
User defined logvars for Django application deployed on uWSGI server
I have deployed a Django application on a uWSGI server, which has the following middleware # myapp/middleware.py from django.utils.deprecation import MiddlewareMixin class LogUserMiddleware(MiddlewareMixin): def process_request(self, request): request.META['REMOTE_USER'] = 'test' The middleware is added in the settings.py file as well # myapp/settings.py MIDDLEWARE = [ ... 'myapp.middleware.LogUserMiddleware', ... ] Then in the uWSGI config file also the logvar is used ... log-format = %(ltime) %(addr){uWSGI} : %(method) %(uri) %(status) %(REMOTE_USER) ... But still the logs show as 19/May/2024:09:01:49 +0000 127.0.0.1{uWSGI} : GET /health_check 200 - Basically the logvar is getting replaced with - instead of showing test Is there any extra config to be done? -
How to run the build command before the build on Digital Ocean App Plateform
I need the json key file to configure my google cloud storage credentials in my settings.py (Django app) `GS_SERVICE_ACCOUNT = "static/GCS_key_api.json" GS_PROJECT_ID = os.getenv('GS_PROJECT_ID') GS_CREDENTIALS = service_account.Credentials.from_service_account_file(GS_SERVICE_ACCOUNT)` Here the logs of the build on App Plateofrm: 2024-05-19T09:24:41.171400485Z [34m╭────────────[34m[30m[44m git repo clone [0m[0m[34m───────────╼[0m 2024-05-19T09:24:41.171433696Z [34m│[0m [34m › fetching app source code[0m 2024-05-19T09:24:41.171437957Z [34m│[0m => Selecting branch "main" 2024-05-19T09:24:41.233929376Z [34m│[0m => Checking out commit "b0f8c02acbc8ef86ba30b50e4295f53a938aa584" 2024-05-19T09:24:41.237120654Z [34m│[0m 2024-05-19T09:24:41.239089601Z [34m│[0m [32m ✔ cloned repo to [35m/workspace[0m[0m 2024-05-19T09:24:41.317807317Z [34m╰────────────────────────────────────────╼[0m 2024-05-19T09:24:41.317827278Z 2024-05-19T09:24:41.492647202Z [34m › configuring build-time app environment variables:[0m 2024-05-19T09:24:41.492841261Z EMAIL_HOST_USER EMAIL_HOST_PASSWORD GS_SERVICE_ACCOUNT_JSON STRIPE_API_KEY SECRET_KEY GS_BUCKET_NAME PUBLIC_GS_BUCKET_NAME EMAIL_HOST GS_PROJECT_ID DEBUG DJANGO_ALLOWED_HOSTS EMAIL_PORT 2024-05-19T09:24:41.492854441Z 2024-05-19T09:24:41.494640715Z [34m › configuring custom build command to be run at the end of the build:[0m 2024-05-19T09:24:41.498131225Z [34m│[0m bin/pre_build.sh 2024-05-19T09:24:41.498140596Z 2024-05-19T09:24:41.567448183Z [34m╭────────────[34m[30m[44m buildpack detection [0m[0m[34m───────────╼[0m 2024-05-19T09:24:41.584376861Z [34m│[0m [34m › using Ubuntu 22.04 stack[0m 2024-05-19T09:24:41.933275054Z [34m│[0m Detected the following buildpacks suitable to build your app: 2024-05-19T09:24:41.933296537Z [34m│[0m 2024-05-19T09:24:41.933299356Z [34m│[0m digitalocean/python-appdetect v0.0.3 2024-05-19T09:24:41.933301358Z [34m│[0m heroku/python v4.242.4 (Python) 2024-05-19T09:24:41.933303328Z [34m│[0m digitalocean/procfile v0.0.4 (Procfile) 2024-05-19T09:24:41.933323594Z [34m│[0m digitalocean/custom v0.1.2 (Custom Build Command) 2024-05-19T09:24:41.933326093Z [34m│[0m 2024-05-19T09:24:41.933329053Z [34m│[0m For documentation on the buildpacks used to build your app, please see: 2024-05-19T09:24:41.933330985Z [34m│[0m 2024-05-19T09:24:41.933332932Z [34m│[0m Python v4.242.4 https://do.co/apps-buildpack-python 2024-05-19T09:24:41.936049330Z [34m╰─────────────────────────────────────────────╼[0m 2024-05-19T09:24:41.936066543Z 2024-05-19T09:24:41.938555872Z [34m╭────────────[34m[30m[44m app build [0m[0m[34m───────────╼[0m 2024-05-19T09:24:42.018292005Z [34m│[0m -----> No … -
Flatten DRF's nested serializer
I have two models for each user, a User model and a Profile model. class User(BaseModel, AbstractUser): username = None image = models.CharField(max_length=300, blank=True, null=True) email = models.EmailField(unique=True) password = models.CharField(max_length=300) emailConfirmed = models.BooleanField(default=False) phoneNumber = models.CharField(max_length=15, blank=True, null=True) phoneNumberConfirmed = models.BooleanField(default=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = UserManager() class Profile(BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='profiles', null=True, blank=True) firstName = models.CharField(max_length=30) lastName = models.CharField(max_length=30) locale = models.CharField(max_length=2) A user can have multiple profiles, but for each locale, a user can have only one profile. And I use these models as a base to create other user models, for example, a Member model: class Member(User): birthdate = models.DateField(blank=True, null=True) class MemberProfile(Profile): member = models.ForeignKey(Member, on_delete=models.CASCADE, related_name='member_profiles', null=True, blank=True) education = models.CharField(max_length=300, blank=True, null=True) address = models.CharField(max_length=300, blank=True, null=True) # other fields only for members Now for the list and create functionalities of this Member model, I've written a ListCreateAPIView like this: @extend_schema(tags=[Namespace.MEMBERS.value]) class MemberListCreateView(generics.ListCreateAPIView): serializer_class = MemberSerializer permission_classes = [IsAuthenticated, IsAdminUser] filter_backends = [filters.DjangoFilterBackend] filterset_class = SearchFilter http_method_names = ["get", "post"] def get_queryset(self): return Member.objects.all() def get_serializer_context(self): context = super().get_serializer_context() context["locale"] = self.kwargs.get("locale", None) return context def create(self, request, *args, **kwargs): return super().create(request, *args, **kwargs) def list(self, request, *args, …