Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Right" way to define helper functions for Django models' Meta classes
I'm trying to simplify a very verbose and repetitive Check constraint for a model, whose logic is currently very hard to parse, factoring out and aptly renaming the repetitive parts. Basically I want to turn this (simplified and abstracted snippet): class MyModel(models.Model): class Meta: constraints = [ models.CheckConstraint( check = ( ( models.Q(foo = True) & ( ( models.Q(field1 = 'X') & models.Q(field2 = 'Y') & models.Q(field3 = 'Z') ) | ( models.Q(field4 = 1) & models.Q(field5 = 2) & models.Q(field6 = 3) ) ) ) | ( models.Q(foo = False) & ( ( models.Q(field1 = 'X') & models.Q(field2 = 'Y') & models.Q(field3 = 'Z') ) | ( models.Q(field4 = 4) & models.Q(field5 = 5) & models.Q(field6 = 6) ) ) ) ), name = 'foo', ), ] Into this: class MyModel(models.Model): class Meta: constraints = [ models.CheckConstraint( check = ( ( models.Q(foo = True) & ( condition1 | condition2 ) ) | ( models.Q(foo = False) & ( condition1 | condition3 ) ) ), name = 'foo', ), ] What I've tried / thought of trying: Factoring out the conditions, both as attributes and methods in Meta itself; that didn't work: TypeError: 'class Meta' got invalid attribute(s): condition1,condition2,condition3; Factoring … -
How to display multiple lines of text in django admin for Headers?
Similar questions that have already been asked are for data fields like in Here and Here But how to split the header in multiple lines? Considering a Django app with model and admin setup like this: models.py from django.db import models class TaskItem(models.Model): group = models.ForeignKey(TaskGroup, on_delete=models.CASCADE) title = models.CharField(max_length=32, null=False, blank=False) description = models.CharField(max_length=45, null=False, blank=False) reward = models.IntegerField(default=1000, null=False, blank=False) admin.py class TaskItemAdmin(admin.ModelAdmin): list_display=['title', 'group', 'reward'] list_filter=('group',) How can I rename headers to Task Title, Task Group and Task Reward with line breaks? -
How to update a list of To-Do items with checkboxes and save changes using React and Django?
I am trying to update a list of To-Do items using React for the frontend and Django for the backend. Each item has a checkbox to mark it as complete or incomplete. When I click the "Save" button, I want the updated data to be sent to the backend via a PUT request. However, I am facing issues with updating the items properly. Here’s my React handleSave function that triggers the PUT request: const handleSave = async (e) => { e.preventDefault(); console.log('handleSave called'); const updatedItems = items.map((item) => { const checkbox = e.target[`c${item.id}`]; console.log(`Processing item id ${item.id}, checkbox value:`, checkbox?.checked); return { id: item.id, todolist: 1, text: item.text, complete: checkbox ? checkbox.checked : false, duration: item.duration, }; }); try { console.log('Payload to send:', updatedItems); const response = await axios.put( `${import.meta.env.VITE_API_URL}/todo-items/1`, // Update the endpoint if needed updatedItems, { headers: { 'Content-Type': 'application/json' }, // Set proper headers } ); console.log('Items updated successfully:', response.data); } catch (error) { console.error('Error updating items:', error.message, error.response?.data); } }; Here’s the Django view handling the request: @api_view(['GET', 'PUT']) def todo_items(request, id): try: ls = ToDoList.objects.get(id=id) except ToDoList.DoesNotExist: return Response({"error": "List not found"}, status=404) if request.method == 'GET': incomplete_items = ls.item_set.filter(complete=False) complete_items = ls.item_set.filter(complete=True) items = … -
Frontend React(next.js) Backend (DJango) and Database (PostGreSQL)
I am working on a small project with this stack Frontend React(next.js) ==> Backend (Django) ==> Database (PostgreSQL). Please advise if this is ok. donor management system (dms) Thanks & Regards Nawaz Mohammed -
Annotate multiple values as JSONObject - parse datetime
I'm annotating my QuerySet as follows, using JSONObject, to obtain multiple fields from Scan: MyModel.objects.annotate( myscan=Subquery( Scan.objects .all() .values(data=JSONObject( id='id', nin='nin', datetime='datetime') )[:1] ) ) I want to get a proper datetime representation though, somehow. When I try to use myscan.datetime, I get the string representation (e.g. datetime': '2024-12-31T09:19:30.221953+00:00. How can I either return the datetime object itself (instead of a string; assuming this is impossible when using JSONObject) or alternatively do a strptime() before returning the string as part of the JSON? Obviously I could parse the string, convert to datetime and then do strptime() again, but that seems like a dirty solution. Any suggestions? -
Django - javascript - ajax does not work with javascript created lines
I have three classes lets say, class Item(models.Model): id = models.AutoField(primary_key=True) # Explicitly define the id column as the primary key itemref = models.IntegerField(blank=True, null=True) code = models.CharField(max_length=150, db_collation='Turkish_CI_AS', blank=True, null=True) tanimlama = models.CharField(max_length=150, db_collation='Turkish_CI_AS', blank=True, null=True) itemname = models.CharField(max_length=150, db_collation='Turkish_CI_AS', blank=True, null=True) class SAFiche(models.Model): nothing important class SALine(models.Model): safiche = models.ForeignKey(SAFiche, on_delete=models.CASCADE) item = models.ForeignKey('accounting.Item', on_delete=models.CASCADE) In views, I have ajax for autocomplate: def item_autocomplete(request): query = request.GET.get('q', '') items = Item.objects.filter( Q(code__icontains=query) | Q(itemname__icontains=query) | Q(tanimlama__icontains=query) )[:10] # Limit to 10 results results = [] for item in items: label = f"{item.code or ''} - {item.itemname or item.tanimlama or ''}" results.append({ 'id': item.id, 'label': label.strip(' -'), }) return JsonResponse(results, safe=False) I properly adjusted rest. This is my forms: class SALineCreateForm(forms.ModelForm): urun_search = forms.CharField( label="Ürün Ara", required=False, widget=forms.TextInput(attrs={ 'placeholder': 'Ürün kodu veya adı...', 'class': 'item-search-input border rounded p-2 w-full', 'autocomplete': 'off' }) ) class Meta: model = SALine fields = [ 'urun', 'miktar' ] widgets = { 'urun': forms.HiddenInput(), 'miktar': forms.NumberInput(attrs={'class': 'w-full form-input rounded-md'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # If editing an existing line, fill the search box with the item name if getattr(self.instance, 'urun_id', None): self.fields['urun_search'].initial = str(self.instance.urun) SALineCreateFormSet = inlineformset_factory( SAFiche, SALine, form=SALineCreateForm, extra=1, … -
React, Django. Gunicorn, nginx , docker setup for production ready and not ablet to server static files for both frontend and backend
This is the current project director for my project as of now Project/ │── .env ├── docker-compose.yml # Docker Compose configuration file │ ├── Frontend/ # React Frontend (Client-side) │ ├── Dockerfile # Dockerfile for React app build │ ├── package.json # React package file │ ├── public/ # Public assets for React │ ├── src/ # React source code │ ├── build/ # React build output (this is where `npm run build` │ ├── nginx.conf └── Backend/ # Django Backend (Server-side) ├── Dockerfile # Dockerfile for Django app build ├── manage.py # Django manage.py file ├── Backend/ # Django application code (models, views, etc.) ├── requirements.txt ├── static/ # Static files (collected by `collectstatic`) ├── media/ # Media files (user-uploaded files) └── .dockerignore # Docker ignore file i have this directory structure where i have 2 folders for backend and front end each is build with Django and react respectively and i have the nginx file in the frontend directory to copy the first build in the frontend container but the thing is that i also share the same volume with the django also but nginx is not ablet to server sttic files to django as well get 404 … -
Django Vercel Deployment Issue | 500: INTERNAL_SERVER_ERROR | ModuleNotFoundError: No module named 'distutils'
I have been trying to deploy a Django App on vercel, it is getting deployed but the website is not working says "This Serverless Function has crashed" Requirements.txt Django==3.1.12 djongo==1.3.7 dnspython==2.7.0 pymongo==3.11.4 psycopg2-binary~=2.9.6 setuptools==75.7.0 vercel.json { "builds": [{ "src": "inventory_management/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } }], "routes": [ { "src": "/(.*)", "dest": "inventory_management/wsgi.py" } ] } The error says, from distutils.version import LooseVersion ModuleNotFoundError: No module named 'distutils' Tried adding setuptools in requirements.txt but still the same issue -
social_core.exceptions.MissingBackend: Missing backend "google-oauth2" entry in Django with Google OAuth2
I'm working on integrating Google OAuth2 in my Django REST Framework project using django-rest-framework and social-django. However, when I try to authenticate using the endpoint: GET /api/o/google-oauth2/?redirect_uri=http://localhost:3000/auth/google I get the following error: social_core.exceptions.MissingBackend: Missing backend "google-oauth2" entry What could be causing the Missing backend "google-oauth2" entry error? Am I missing any configuration, or could there be an issue with the library versions? Any help or guidance would be appreciated. Added the following to my settings.py: AUTHENTICAION_BACKEN,DS =[ 'django.contrib.auth.backends.ModelBackend', 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.facebook.FacebookOAuth2', ] SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'openid', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ] The redirect_uri (http://localhost:3000/auth/google) matches the one registered in the Google API Console. -
Django annotation from different sources
I'm trying to build following annotation, essentially looking up the nin field from a person either from the IDcard or from the Person model. .annotate( checkins_scan=Scan.objects.filter(models.Q(nin=OuterRef("person__idcard__nin") | models.Q(national_number=OuterRef("person__nin"))) .values( data=JSONObject(id="id", nin="nin", datetime="datetime") )[:1] ) However, I get following error: NotImplementedError: Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations. Looks like I'll need bitor(), but I'm not getting any further with the basic examples I'm finding (e.g. documentation here). When I try to work with F() I get TypeError: F.__init__() got an unexpected keyword argument 'nin'. Any clues on how to properly do this? -
VSCode Test Explorer hangs despite no errors in the output & all tests being collected (in the output)
I have been having a lot of issues with Test Explorer in VSCode. It has been working fine up until last week. I was writing new tests and clicked "Refresh Tests" and then it suddenly (and pretty randomly) stopped working - specifically it "discovers" tests forever. And that is despite the fact that the output shows that the tests seem to be discovered correctly in the output window: The tests are also all passing if I run them with standard pytest terminal command: My directory structure is as follows: application ├── backend │ ├── src | ├── |── __init__.py | ├── |── manage.py | ├── |── app1 | ├── |── ├── __init__.py | ├── |── ├── folder1 | ├── ├── ├── ├── __init__.py | ├── |── ├── ├── views.py | ├── |── ├── ├── class1.py | ├── |── ├── ├── class2.py | ├── ├── ├── ├── tests | ├── ├── ├── ├── ├── __init__.py | ├── ├── ├── ├── ├── test_class1.py | ├── ├── ├── ├── ├── test_class2.py | ├── ├── ├── ├── ├── test_views.py | ├── |── ├── folder2 | ├── ├── ├── ├── __init__.py | ├── |── ├── ├── views.py | ├── |── ├── ├── class1.py | ├── … -
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 …