Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to dynamically create and manage SQL-like tables, data, and relationships in a MongoDB-based system?
I'm building a web application where users can execute SQL queries on predefined tables for an exam module. The backend is in Django, and the database is MongoDB. I want to allow admins to dynamically: Create table schemas (table name, columns, data types, primary keys). Insert data into these tables. Define relationships between tables (e.g., foreign keys). Validate and execute SQL queries submitted by users based on the stored table schemas and relationships. The goal is to minimize backend involvement by providing a user-friendly admin interface for managing tables and relationships. I am looking for best practices or suggestions on: Efficiently storing table schemas and relationships in MongoDB. Dynamically executing and validating SQL-like queries based on these schemas. Simplifying the admin interface for managing tables and relationships in the frontend. Any advice, code snippets, or recommended libraries/tools would be appreciated. -
Gmail with Oauth rejects my token/password
I am trying to send mail from Django. I've tried two different ways, both of which fail in different ways. When I tried using an app password, I had no errors, but the email just never arrived. And the sender's outbox is empty, too. But that was after I tried the modern method, OAuth. After a process that I would never have finished without ChatGPT (because nobody else has created a guide that I can find), I set up something that almost works. I have a file with a refresh token in it, and a custom backend that uses it. But when it's time to send an email, I'm told "Username and Password not accepted." Here's what the token file is like: { "token": "[secret]", "refresh_token": "[secret]", "token_uri": "https://oauth2.googleapis.com/token", "client_id": "[secret]", "client_secret": "[secret]", "scopes": ["https://www.googleapis.com/auth/gmail.send"], "universe_domain": "googleapis.com", "account": "", "expiry": "2025-01-05T07:39:06.980351Z" } And this is the backend: from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from django.core.mail.backends.smtp import EmailBackend from pathlib import Path import os class GmailOAuth2Backend(EmailBackend): def _get_access_token(self): dir = Path(__file__).resolve().parent file = os.path.join(dir, 'oauth2tokenfile.secret.json') creds = Credentials.from_authorized_user_file(file) if creds.expired and creds.refresh_token: creds.refresh(Request()) return creds.token def open(self): self.password = self._get_access_token() super().open() And finally, my settings EMAIL_BACKEND = "[secret].GmailOAuth2Backend" EMAIL_HOST … -
how to create a virtual try on website using django
I encountered a CUDA (NVIDIA) version error while attempting to set up a virtual try-on website for e-commerce. I tried several Python versions, but CUDA is not compatible with Django. If I downgrade to resolve the CUDA issue, other packages become incompatible. I need the full source code and an explanation for implementing a virtual try-on e-commerce website. -
page not found error when using python social auth login for okta
I am getting a "Backend not found" error when trying to setup okta oidc login using social-auth-app-django 5.4.2 here are the settings: 'social_django' is added to INSTALLED_APPS 'social_django.middleware.SocialAuthExceptionMiddleware' is added to MIDDLEWARE "social_django.context_processors.backends" and "social_django.context_processors.login_redirect" are added to the list in TEMPLATES['OPTIONS']['context_processors'] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'social_core.backends.okta_openidconnect.OktaOpenIdConnect', ] LOGIN_URL = 'auth/login/okta_openidconnect/' and in the list of project urls, this is added path('auth/', include('social_django.urls', namespace='social')) when i go to the login url, I get a 404 page not found error Backend not found Request Method: GET Request URL: https://my.site/auth/login/okta_openidconnect/?next=/en-us/ Raised by: social_django.views.auth Using the URLconf defined in xxx.urls, Django tried these URL patterns, in this order: ... 17. en-us/ auth/ login/<str:backend>/ [name='begin'] The current path, en-us/auth/login/okta_openidconnect/, matched the last one. there are other settings, like SOCIAL_AUTH_OKTA_OPENIDCONNECT_KEY and the SOCIAL_AUTH_PIPELINE, which i'm sure are correct and i believe that even if they were not correct, it's unrelated to not having the proper backend. so does anyone see a mistake in this setup that could be causing the backend fail? -
playwright with django: 502 Bad Gateway Error
My webapp doesn't work for any portion that uses playwright. Everything works in localhost (including playwright). When trying to view the home page (no playwright), it works 100%. When trying to use code from the library playwright, it gives me a: 502 Bad Gateway nginx/1.18.0 (Ubuntu) What can I do to troubleshoot this? I tried disabling firewall, but that didn't make difference. I tried debugging by throwing an exception for each line of code. Sometimes it moves a few lines further and other times it doesn't move a few lines further. Again, only code that uses playwright will give me this error. I'm using Django 5.1.4. Playwright is latest version. Here's some code from playwright: try: await page.goto('https://pantry.plentifulapp.com/login') await expect(page.get_by_test_id("LoginForm-44")).to_be_visible(timeout=3000) except: content = "Plentiful is down." return content #Find email input and type it. await page.get_by_test_id("LoginForm-47").click() await page.keyboard.type(username) #find password input, type it, and then press enter. await page.get_by_test_id("LoginForm-53").click() await page.keyboard.type(password) await page.keyboard.press("Enter") -
502 Bad Gateway Elastic Beanstalk, No Module named "ebdjango"
I'm trying to deploy a django application using elastic beanstalk, I've followed all the steps from the AWS documentation and I get a 502 bad gateway error. I looked through the elastic beanstalk logs like similar questions suggested and the same error keeps appearing that I didn't see in any other posts. Jan 6 20:42:24 ip-172-31-32-9 web: ModuleNotFoundError: No module named 'ebdjango' I can only find similar questions about django module not ebdjango, and pip install obviously doesn't work. I've included other file info that might be relevant. If anything else is needed I'm happy to provide it. django.config file option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango.wsgi:application aws:autoscaling:launchconfiguration: DisableIMDSv1: true' config.yml branch-defaults: default: environment: django-env-2 group_suffix: null environment-defaults: django-env: branch: null repository: null global: application_name: django-env-2 branch: null default_ec2_keyname: null default_platform: Python 3.8 default_region: eu-west-2 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: null sc: null workspace_type: Application EB Error Logs Jan 6 20:42:25 ip-172-31-32-9 web: Traceback (most recent call last): Jan 6 20:42:25 ip-172-31-32-9 web: File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/gunicorn/arbiter.py", line 608, in spawn_worker Jan 6 20:42:25 ip-172-31-32-9 web: worker.init_process() Jan 6 20:42:25 ip-172-31-32-9 web: File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/gunicorn/workers/gthread.py", line 94, in init_process Jan 6 20:42:25 ip-172-31-32-9 web: super().init_process() Jan 6 20:42:25 ip-172-31-32-9 web: … -
Need help fixing a Django 404 error, not finding a static page using URLConf
My Django project is a single-application website where the homepage shows articles/posts from my database, and will have pages for tag topics and year/month archives. All other pages are static pages for photo and video galleries, and an about page — they don't use the database at all. I'm trying to get one of the static pages to display, but I keep running into a 404 error with the following (note: I replaced the application's name with "<app_name>"): No article found matching the query Request Method: GET Request URL: http://127.0.0.1:8000/illustrations Raised by: <app_name>.views.ArticleDetailView Using the URLconf defined in website.urls, Django tried these URL patterns, in this order: admin [name='home'] <slug:slug> [name='article_detail'] The current path, illustrations, matched the last one. The homepage shows all articles in ListView, and you can click individual articles to view them in DetailView with the designated slug as the URL. The "illustrations" file is a separate static HTML page I'll use that has nothing to do with the database or either of the List or Detail views. I can't tell if I should make the homepage a separate app, or if I just need to change my URLs/Views files. (I'm learning Django and Python, so I'm … -
What is the most secured approach to prevent html video download from a django website
I have a website that i want to do the following: prevent users from downloading the videos. I need the best practice ensure that my videos can only be played within the website and no where else I tried to disguise the video source link to blob url object but it's downloadable. Even when I copy the blob url object in to browser the video still plays, that another thing i need to prevent. PLEASE HELP! -
How to run a Redis listener in Django when the server starts?
I'm working with Django and I have a Redis listener that I run with the following custom command: import os import asyncio from django.core.management.base import BaseCommand from notifications.core.redis_listener import RedisListener class Command(BaseCommand): help = 'Listen for notifications with metadata from Redis in real-time' def handle(self, *args, **kwargs): redis_host = os.getenv('REDIS_HOST') redis_port = int(os.getenv('REDIS_PORT')) redis_password = os.getenv('REDIS_PASSWORD') redis_channel = 'notifications_channel' # Redis channel to subscribe to ssl = os.getenv('REDIS_SSL', 'False') == 'True' # Conditionally Use "ssl_cert_reqs" if ssl: redis_listener = RedisListener( redis_host=redis_host, redis_port=redis_port, redis_password=redis_password, redis_channel=redis_channel, ssl=ssl, ssl_cert_reqs='none' ) else: redis_listener = RedisListener( redis_host=redis_host, redis_port=redis_port, redis_password=redis_password, redis_channel=redis_channel, ssl=ssl, ssl_cert_reqs='none' ) # Run the listener function with asyncio loop = asyncio.get_event_loop() loop.run_until_complete(redis_listener.listen_to_redis()) Currently, I start the Redis listener by running: python manage.py listen_redis However, I want the Redis listener to start automatically when I run the Django development server with: python manage.py runserver I would like this Redis listener to run concurrently with the Django development server without needing to manually start it via a custom management command. How can I achieve this? In my apps.py I tried this - from django.apps import AppConfig import os import threading import asyncio from notifications.core.redis_listener import RedisListener from django.db.backends.signals import connection_created from django.db import connections class … -
Django query is case sensitive after moving to MariaDB
I have a Django project that can perform a query using a person's name as show in the attached code. def get_queryset(self): query = self.request.GET.get('query') if query: query = " ".join(query.split()) if query.isdigit(): qs = Patient.objects.filter(Q(full_name__contains=query) | Q(patient_id__contains=query)).order_by('patient_id') else: qs = Patient.objects.filter(Q(full_name__contains=query) | Q(patient_id__contains=query)).order_by(Lower('full_name')) else: qs = Patient.objects.order_by(Lower('full_name')) return qs This works in a case insensitive manner in SQLite3, which is what I want. I recently moved the project to MariaDB and now the query is case sensitive. I have checked to collation on the database, table, column, ... and it is set to utf8mb3_general_ci which by my understanding should result in a case insensitive search. Interestingly enough, doing the interactive query: select full_name from patients_patient where full_name like 'ana maria%'; results in a case insensitive search. Any ideas why the query in my code is case sensitive and how to make it case insensitive? -
Django FieldError: Unknown field(s) (usable_password) specified
I am facing this FieldError while trying to add User in Users in admin panel. When I click on add user this error pops up. I hac=ve not used usable_password in my code anywhere, and tried to multiple method to resolve this issue by deleting db.sqlite3, migration, and then redoing the makemirations. One more thing is that I changed the spelling of class in models.py (after doing migrations and then did migration again it successfully created the migration file). I want to understand why is this happening one more thing i encountered similar error a while back with different project and I don't know how it got resolved that time. FieldError at /admin/accounts/customuser/add/ Unknown field(s) (usable_password) specified for CustomUser. Check fields/fieldsets/exclude attributes of class CustomUserAdmin. Request Method: GET Request URL: http://127.0.0.1:8000/admin/accounts/customuser/add/ Django Version: 5.1.4 Exception Type: FieldError Exception Value: Unknown field(s) (usable_password) specified for CustomUser. Check fields/fieldsets/exclude attributes of class CustomUserAdmin. Exception Location: C:\Users\Learning Django\blog-api\.venv\Lib\site-packages\django\contrib\admin\options.py, line 841, in get_form Raised during: django.contrib.auth.admin.add_view Python Executable: C:\Users\Learning Django\blog-api\.venv\Scripts\python.exe Python Version: 3.12.2 Python Path: ['C:\\Users\\Desktop\\Learning ' 'Django\\blog-api\\django_project', 'C:\\Python312\\python312.zip', 'C:\\Python312\\DLLs', 'C:\\Python312\\Lib', 'C:\\Python312', 'C:\\Users\\Learning ' 'Django\\blog-api\\.venv', 'C:\\Users\\Learning ' 'Django\\blog-api\\.venv\\Lib\\site-packages'] I am attaching code of models.py, forms.py, and admin.py bellow: models.py from django.db import models # … -
Product cards are not displayed in categories
There was a problem in displaying products that are sorted by category in the "Products by category" section of the site. The display of goods by category is prescribed in "list.html ". Views have been created for these products, but the product cards themselves are not displayed. That's the problem. I guess I made a mistake somewhere in the cycles, and now these product cards just don't appear. I did a review, but I didn't find anything.. I ask you to help me with this problem, I will be grateful. [enter image description here](https://i.sstatic.net/eIg0eIvI.png) I tried to rebuild the HTML list file, looked at the views and urls to see if they were specified correctly, and looked at the methods, but nothing worked. P.S: Project on GitHub: https://github.com/fdavis10/django-site -
Deploy Django app on Railway.app with Postgres
I need help deploying my Django app on the railway.app. I am still developing the app, but it is already in good shape, so I decided to try the deployment. It works fine on my local mac, I used Postgres as db, running into a docker. When I try to deploy it on the railway.app, I added a Dockerfile: # Use an official Python runtime as a parent image FROM python:3.10-slim # Set environment variables to avoid interactive prompts during installation ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set the working directory WORKDIR /app # Install dependencies COPY requirements.txt /app/ RUN pip install --no-cache-dir -r requirements.txt # Copy the entire project into the container COPY . /app/ # # Set the default Django app for commands # ENV DJANGO_APP mywebsite # Expose the port the app runs on EXPOSE 8000 # Run the application CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] Then I set up the environment variables on the dashboard for my django app, to connect with the postgress service: ${{Postgres.PGDATABASE}} ${{Postgres.PGUSER}} ${{Postgres.PGPASSWORD}} ${{Postgres.PGHOST}} ${{Postgres.PGPORT}} All shall be linked using the following piece of code in the settings.py: os.environ.setdefault("PGDATABASE", "mydatabase") os.environ.setdefault("PGUSER", "myuser") os.environ.setdefault("PGPASSWORD", "mypassword") os.environ.setdefault("PGHOST", "localhost") os.environ.setdefault("PGPORT", "5432") DATABASES = { … -
getting the choice names from an array of values in Django Rest Framework
I am trying to get the choice labels from a field that stores an array of choices - I am able to get the label when the field has a single value. Here is the model: class TobaccoUse(models.Model): tu_id = models.AutoField(primary_key=True) patient_id_fk = models.ForeignKey('patient_management.PatientInformation', on_delete=models.CASCADE) SMOKING_STATUS_CHOICES = [ ('N', 'Never Smoked'), ('P', 'Past Smoker'), ('C', 'Current Smoker') ] tu_smoking_status = models.CharField(max_length=1, choices=SMOKING_STATUS_CHOICES) OTHER_USE_CHOICES = [ ('P', 'Pipe'), ('C', 'Cigar'), ('S', 'Snuff'), ('CH', 'Chew') ] tu_other_use = ArrayField(models.CharField(max_length=2, choices=OTHER_USE_CHOICES, null=True, blank=True), size=4, default=list, null=True, blank=True) tu_packs_per_day = models.DecimalField(blank=True, null=True, max_digits=4, decimal_places=1) tu_years_smoked = models.PositiveSmallIntegerField(blank=True, null=True) tu_quit_date = models.DateField(blank=True, null=True) tu_is_active = models.BooleanField(default=True) The view: class ListTobaccoUseOptions(APIView): def get(self, request): statusChoices = [] otherChoices = [] for ssc in TobaccoUse.SMOKING_STATUS_CHOICES: statusChoices.append({'label': ssc[1], 'value': ssc[0]}) for soc in TobaccoUse.OTHER_USE_CHOICES: otherChoices.append({'label': soc[1], 'value': soc[0]}) try: smoking_status_categories = {'status_categories': statusChoices, 'other_use_categories': otherChoices} return Response(smoking_status_categories, status=status.HTTP_200_OK) except Exception as e: return Response(data={'error': str(e)}, status=status.HTTP_400_BAD_REQUEST) And the serializers: class PatientMedicalHxSerializer(serializers.ModelSerializer): prognosis = serializers.SerializerMethodField() primary_diagnosis = serializers.SerializerMethodField() surgical_diagnoses = serializers.SerializerMethodField() secondary_diagnoses = serializers.SerializerMethodField() wellness_screenings = serializers.SerializerMethodField() tobacco_use = serializers.SerializerMethodField() vape_use = serializers.SerializerMethodField() class Meta: model = PatientInformation fields = ('primary_diagnosis', 'secondary_diagnoses', 'surgical_diagnoses', 'prognosis', 'wellness_screenings', 'tobacco_use', 'vape_use') def get_primary_diagnosis(self, patientinformation): qs = PatientToPrimaryDiagnosis.objects.filter(patient_id_fk = patientinformation, ptpd_is_active = True) serializer … -
django-rosetta :Nothing to translate! You haven't specified any languages in your settings file
I'm using django-rosetta 0.10.0 with Django, and I have django.po and django.mo files set up correctly. Everything works fine with Django's built-in translation system, and I can successfully use translations. However, when I open Rosetta, it cannot find any translations from my local apps or third-party apps (e.g., rosetta or debug-toolbar). Instead, I see the following message in the Rosetta interface: Nothing to translate! You haven't specified any languages in your settings file, or haven't yet generated a batch of translation catalogs. I’ve already set up my translations in the correct paths and ensured the locale files exist. Here's some additional information about my setup: Rosetta version: 0.10.0 My app structure follows the standard pattern, with locale directories inside each app (e.g., myapp/locale/fa/LC_MESSAGES/django.po). I have defined LANGUAGE_CODE = 'fa-ir' LANGUAGES = ( ('en','English'), ('fa','Persian') ) TIME_ZONE = 'Asia/Tehran' USE_I18N = True USE_L10N = True USE_TZ = True, in settings.py. Do I need to explicitly define LOCALE_PATHS for each of my apps in settings.py, or should Rosetta automatically detect the locale directories inside the apps? If it’s necessary to specify LOCALE_PATHS, how should I configure it for multiple apps with translations? As I'm a beginner in Django, I would appreciate any … -
Django local server is not running
(myenv) PS E:\Pioneer.Solution\PythonFile\API1> python manage.py runserver Performing system checks... usage: manage.py [-h] [-c] manage.py: error: unrecognized arguments: runserver I'm try to run the local server. it was running earlier but suddenly the same thing stopped. Please help me out in this matter. manage.py: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'API1_sub.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHON environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
I can't upload an image to my database at all
I'm using django ninja back end the code works but when I try to send it through an application that I'm making using javascript or even with bash it doesn't work i've tryed `def upload_media(request, nome:str, imgurl: UploadedFile ): usuarios = Media.objects.all() Media.objects.create(nome = nome,imgurl=imgurl) return 1` and class mediaSchema(Schema): nome : str imgurl: UploadedFile `@api.post('tst/', response=mediaSchema) def upload_media2(request, infos : mediaSchema): media = infos.dict() infos = Media(**media) infos.save() return 1` -
Converting Nested Query string requests to a dictionary
I'm experiencing some difficulties converting a querystring data to a well formed dictionary in my view. Here's my view class VendorPayloadLayerView(generics.GenericAPIView): permission_classes = (permissions.AllowAny,) def get(self, request, *args, **kwargs): print("Here's the request *****") print(request) payload = request.GET print("Here's the decoded queryDict data") print(payload) data = payload.dict() print("Here's the dictionary") print(data) Here is the request to the view: <rest_framework.request.Request: GET '/turnalerts/api/v2/vendor?%7B%22_vnd%22:%20%7B%22v1%22:%20%7B%22author%22:%20%7B%22id%22:%20%22d2e805b5-4a25-4102-a629-e6b67c798ad6%22,%20%22name%22:%20%22WhatsApp%20Business%20Cloud%20API%22,%20%22request_id%22:%20%22GBV3LTlUEUtfjuMHaDYi%22,%20%22type%22:%20%22SYSTEM%22%7D,%20%22card_uuid%22:%20null,%20%22chat%22:%20%7B%22assigned_to%22:%20%7B%22id%22:%20%2278c711b6-2673-cd8b-0fd9-9a6f03bbcdc5%22,%20%22name%22:%20%22Chima%20Chinda%22,%20%22type%22:%20%22OPERATOR%22%7D,%20%22contact_uuid%22:%20%225ba732cf-d424-4163-9d73-98680d4f53f9%22,%20%22inserted_at%22:%20%222022-05-10T10:15:38.808899Z%22,%20%22owner%22:%20%22%202349039756628%22,%20%22permalink%22:%20%22https://whatsapp-praekelt-cloud.turn.io/app/c/ebd12728-e787-4f29-b938-1059b67f4abd%22,%20%22state%22:%20%22OPEN%22,%20%22state_reason%22:%20%22Re-opened%20by%20inbound%20message.%22,%20%22unread_count%22:%2018,%20%22updated_at%22:%20%222024-12-28T22:17:48.825870Z%22,%20%22uuid%22:%20%22ebd12728-e787-4f29-b938-1059b67f4abd%22%7D,%20%22direction%22:%20%22outbound%22,%20%22faq_uuid%22:%20null,%20%22in_reply_to%22:%20null,%20%22inserted_at%22:%20%222024-12-28T22:17:48.817259Z%22,%20%22labels%22:%20[],%20%22last_status%22:%20null,%20%22last_status_timestamp%22:%20null,%20%22on_fallback_channel%22:%20false,%20%22rendered_content%22:%20null,%20%22uuid%22:%20%227d5fc64e-fd77-325f-8a50-6475e4496775%22%7D%7D,%20%22from%22:%20%2227726968450%22,%20%22id%22:%20%22wamid.HBgNMjM0OTAzOTc1NjYyOBUCABEYEjdCMTJFNUZDNzNFQjkxQ0IyRQA%27:%20%27%22,%20%22preview_url%22:%20false,%20%22recipient_type%22:%20%22individual%22,%20%22text%22:%20%7B%22body%22:%20%22The%20MomConnect%20ADA%20Symptom%20Checker%20is%20unfortunately%20no%20longer%20available.%20%5C%5Cn%5C%5CnPlease%20reply%20*ASK*%20if%20you%20have%20questions%20or%20need%20help.%22%7D,%20%22timestamp%22:%20%221735424268%22,%20%22to%22:%20%222349039756628%22,%20%22type%22:%20%22text%22%7D'> Here's the decoded queryDict with request.GET <QueryDict: {'{"_vnd": {"v1": {"author": {"id": "d2e805b5-4a25-4102-a629-e6b67c798ad6", "name": "WhatsApp Business Cloud API", "request_id": "GBV3LTlUEUtfjuMHaDYi", "type": "SYSTEM"}, "card_uuid": null, "chat": {"assigned_to": {"id": "78c711b6-2673-cd8b-0fd9-9a6f03bbcdc5", "name": "Chima Chinda", "type": "OPERATOR"}, "contact_uuid": "5ba732cf-d424-4163-9d73-98680d4f53f9", "inserted_at": "2022-05-10T10:15:38.808899Z", "owner": " 2349039756628", "permalink": "https://whatsapp-praekelt-cloud.turn.io/app/c/ebd12728-e787-4f29-b938-1059b67f4abd", "state": "OPEN", "state_reason": "Re-opened by inbound message.", "unread_count": 18, "updated_at": "2024-12-28T22:17:48.825870Z", "uuid": "ebd12728-e787-4f29-b938-1059b67f4abd"}, "direction": "outbound", "faq_uuid": null, "in_reply_to": null, "inserted_at": "2024-12-28T22:17:48.817259Z", "labels": [], "last_status": null, "last_status_timestamp": null, "on_fallback_channel": false, "rendered_content": null, "uuid": "7d5fc64e-fd77-325f-8a50-6475e4496775"}}, "from": "27726968450", "id": "wamid.HBgNMjM0OTAzOTc1NjYyOBUCABEYEjdCMTJFNUZDNzNFQjkxQ0IyRQA\': \'", "preview_url": false, "recipient_type": "individual", "text": {"body": "The MomConnect ADA Symptom Checker is unfortunately no longer available. \\\\n\\\\nPlease reply *ASK* if you have questions or need help."}, "timestamp": "1735424268", "to": "2349039756628", "type": "text"}': ['']}> Lastly, here's the dictionary as payload.dict() Here's the dictionary {'{"_vnd": {"v1": {"author": {"id": "d2e805b5-4a25-4102-a629-e6b67c798ad6", "name": "WhatsApp Business Cloud API", "request_id": "GBV3LTlUEUtfjuMHaDYi", "type": "SYSTEM"}, "card_uuid": null, "chat": {"assigned_to": {"id": … -
I have a scheduling task and would like to ask everyone for some suggestions
I have a long verbatim transcript, possibly exceeding 50,000 words. I’ve written a program to split each person’s dialogue into BeforeTranscriptSegment. However, I have several issues, which I’ve listed below. Please provide me with some suggestions. Thank you. By default, I use Gemini for translation because its input token count and output token count meet my expectations. The Gemini plan I’m using has a RateLimit, so I want the API request for translation to - trigger only once every 4 seconds. If there is no transcript to translate at the moment, I’d also like the 4-second worker not to trigger. If there are untranslated segments or if an API call returns an error, I want to implement a retry mechanism. Could you suggest a good way to design this task? Thank you. -
There is some basics I do not understand here regarding custom user models
I wanted to delete a user. After a bit of struggeling I ended up like this: views.py the_user = get_user_model() @login_required def del_user(request): email = request.user.email the_user.objects.filter(email=email).delete() messages.warning(request, "bruker slettet.") return redirect("index") But I really do not understand. In the line email = request.user.email. Why is it not email = request.the_user.email There is some basics I do not understand here regarding custom user models. Is this because the user is refering to the AbstractBaseUser? Please excuse me for asking this. -
How to Send List of IDs via multipart/form-data in Django REST Framework
I am working on a Django REST Framework API where I need to send a list of IDs in a multipart/form-data request to create a many-to-many relationship in the database. While everything works perfectly when using JSON as the request format, I face issues when switching to multipart/form-data because the list of IDs doesn't serialize correctly. Here's my serializer: class AddOrUpdateContractSerializer(serializers.ModelSerializer): deputy_agent = serializers.ListField( child=serializers.IntegerField(), required=False, allow_empty=False ) product_type = serializers.ListField( child=serializers.IntegerField(), required=False, allow_empty=False ) referral_type = serializers.ListField( child=serializers.IntegerField(), required=False, allow_empty=False ) customer_id = serializers.IntegerField(required=False) class Meta: model = Contract exclude = ["id", "product", "is_deleted", "state", "customer"] Here's my view class AddContract(APIView): @extend_schema(request=AddOrUpdateContractSerializer, tags=["contract"]) def post(self, request): serialized_data = AddOrUpdateContractSerializer(data=request.data) if serialized_data.is_valid(raise_exception=True): service = ContractService( serialized_data=serialized_data.validated_data, user=request.user ) service.create_contract() return Response( status=status.HTTP_200_OK, data={"detail": "contract created successfully"}, ) And the service for creating the contract: def create_contract(self): items = ["customer_id", "deputy_agent", "product_type", "referral_type"] customer = CustomerSelector.get_customer_by_id( self.serialized_data.get("customer_id", None) ) deputy_agent = self.serialized_data.get("deputy_agent", None) product_type = self.serialized_data.get("product_type", None) referral_type = self.serialized_data.get("referral_type", None) self.remove_unnecessary_items(items) contract = Contract(customer=customer, **self.serialized_data) contract.full_clean() contract.save() if deputy_agent: deputy_agents = DeputyAgent.objects.filter(id__in=deputy_agent) contract.deputy_agent.add(*deputy_agents) if product_type: product_types = ComboBoxsOptions.objects.filter(id__in=product_type) contract.product_type.add(*product_types) if referral_type: referral_types = ComboBoxsOptions.objects.filter(id__in=referral_type) contract.referral_type.add(*referral_types) PROBLEM When sending the data as multipart/form-data, lists like deputy_agent, product_type, and referral_type are received … -
Multipe one-to-many relation between two models
I am stuck on a question that I really need help in so I was creating a route finder and I have created a model of the vehicle with 2 relations start_location and final_location. I want them to be foreign keys as I don't want to have multiple options when selecting start and final location and foreign key defines one-to-many relation that means one location can have multiple vehicle but one vehicle can't be related to multiple location. So my question is will Django Give me error if I create multiple foreign key fields and connect to location that I think (I may be wrong) will create many-to-many relation Thank you for your insight class Destination(models.Model): name = models.CharField(max_length=100) state = models.ForeignKey(State, on_delete=models.CASCADE,related_name="destination") country = models.ForeignKey(Country, on_delete=models.CASCADE,related_name="destination") class vehicle(models.Model): start_time = models.CharField(max_length=10) reaching_time = models.CharField(max_length=10) startdestination = models.ForeignKey(Destination, on_delete=models.CASCADE,related_name="startdestinations") subdestination = models.ForeignKey(Destination, on_delete=models.CASCADE,related_name="subdestinations") finaldestination = models.ForeignKey(Destination, on_delete=models.CASCADE,related_name="finaldestinations") fare = models.IntegerField() confirmed = models.BooleanField() distance = models.IntegerField() -
Django is not updating on MacOS
Wanted to start working with Django on MacOS although I am not able to manage to install the last version of Django. Python version is 3.8.8 Installing Django with ´pip install Django´results: Requirement already satisfied: django in ./opt/anaconda3/lib/python3.8/site-packages (4.2.16) Requirement already satisfied: sqlparse>=0.3.1 in ./opt/anaconda3/lib/python3.8/site-packages (from django) (0.5.1) Requirement already satisfied: backports.zoneinfo in ./opt/anaconda3/lib/python3.8/site-packages (from django) (0.2.1) Requirement already satisfied: asgiref<4,>=3.6.0 in ./opt/anaconda3/lib/python3.8/site-packages (from django) (3.8.1) Requirement already satisfied: typing-extensions>=4 in ./opt/anaconda3/lib/python3.8/site-packages (from asgiref<4,>=3.6.0->django) (4.12.2) Trying to update it with ´pip install -U Django´ Requirement already satisfied: Django in ./opt/anaconda3/lib/python3.8/site-packages (4.2.16) Collecting Django Downloading Django-4.2.17-py3-none-any.whl (8.0 MB) 8.0 MB 5.4 MB/s Requirement already satisfied: asgiref<4,>=3.6.0 in ./opt/anaconda3/lib/python3.8/site-packages (from Django) (3.8.1) Requirement already satisfied: sqlparse>=0.3.1 in ./opt/anaconda3/lib/python3.8/site-packages (from Django) (0.5.1) Requirement already satisfied: backports.zoneinfo in ./opt/anaconda3/lib/python3.8/site-packages (from Django) (0.2.1) Requirement already satisfied: typing-extensions>=4 in ./opt/anaconda3/lib/python3.8/site-packages (from asgiref<4,>=3.6.0->Django) (4.12.2) Installing collected packages: Django Attempting uninstall: Django Found existing installation: Django 4.2.16 Uninstalling Django-4.2.16: Successfully uninstalled Django-4.2.16 Successfully installed Django-4.2.17 Trying to force the version with ´python -m pip install Django==5.1.4´ results: ERROR: Could not find a version that satisfies the requirement Django==5.1.4 ERROR: No matching distribution found for Django==5.1.4 -
You don’t have permission to view or edit anything. Django Admin. Web-site for school
I am working on a school website where there is a superadmin who can create other users, but the regular administrators (with the is_staff permission) should not have access to the User model. However, they should have access to other models. Currently, when I log in as a regular administrator (is_staff), I receive the error "You don’t have permission to view or edit anything." On the other hand, everything works fine when I log in as the superadmin (is_staff and is_superuser). Could you help me figure out how to configure the permissions properly, so that the regular administrators don't have access to the User model, but can still work with other models? managers.py from django.contrib.auth.models import BaseUserManager class CustomUserManager(BaseUserManager): def _create_user(self, username, position, password, is_staff, is_superuser, **extra_fields): if not username: raise ValueError("Вы не ввели username!") if not password: raise ValueError("Вы не ввели пароль!") user = self.model( username=username, position=position, is_active=True, is_staff=is_staff, is_superuser=is_superuser, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, position="Администратор", password=None, **extra_fields): return self._create_user(username, position, password, is_staff=False, is_superuser=False, **extra_fields) def create_superuser(self, username, password=None, **extra_fields): return self._create_user( username, position="Главный администратор", password=password, is_staff=True, is_superuser=True, **extra_fields ) models.py: from django.contrib.auth.models import ( AbstractBaseUser, PermissionsMixin, ) from django.db import models from .managers import … -
How to attach a VPC to a Lambda through fromFunctionAttributes in CDK?
I manage infrastructure through CDK, except for stuff created by zappa for a Django application. Now, I need to connect such Lambda to the RDS cluster: following this guide I need to attach the Lambda to RDS's VPC, assign all subnets and use a SG different than RDS VPC. However, if can retrieve Zappa's Lambda only through Function.fromFunctionAttributes() which doesn't allow then to specify the vpc as we would create the Lambda inside CDK. How do I solve this?