Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Choices not being rendered in template
Working in Django. I've added choices and the necessary field in my model. The choices are well populated in the admin site, but not rendered in the template. I've double checked several times and everything seems right so I don't understand why the choices aren't rendered in the template. Could it be related to the CSS? I'm using materialize. I've added the .input-field class and initialized the select element as per the materialize documentation. Nothing changed. This is my code: model: class Grocery(models.Model): """ Model to create a grocery_list """ CATEGORIES = [("groceries", "Groceries"), ("school", "School"), ("hardware", "Hardware"), ("travel", "Travel"), ("gifts", "Gifts"), ("decoration", "Decoration"), ("lifestyle", "Lifestyle"), ("wishlist", "Wishlist")] name = models.CharField(max_length=500, default='My grocery list') category = models.CharField(max_length=20, choices=CATEGORIES, default='Shopping') form: class GroceryForm(forms.ModelForm): """ Form to create a grocery shopping list """ class Meta: model = Grocery fields = ['name', 'category', 'shop', 'item'] template: {% block title %}Create shopping list{% endblock %} {% block content %} <div class="container row"> <div class="col s10 m8 push-s1 push-m2"> <h1 class="center-align">Create a grocery shopping list</h1> <div class="divider"></div> <div class="input-field section"> <form method="POST"> {% csrf_token %} {{ form.media }} {{ form.as_p }} <button type="submit" class="waves-effect btn">Create list</button> </form> </div> </div> </div> {% endblock %} JS // … -
TinyMCE data setting issue
Actually i am trying setup data in tinyMCE editor. But, before the tinyMCE editor gets its initialization, function which set data in tinyMCE calls. So, when tinyMCE is loaded, it is with null data. Actually in one page i have around 10-12 editors. At first i started directly form data to load into tinyMCE from serverside in python django. But, it generates missing of data in some of the last editors. So, I decided to set data from client side through javascript. But I could not able to handle that my data setting function call, after the initialization of tinyMCE. So, please help to handle missing data in some of editors. -
celery running issue on raliway
inside the Procfile of my django app im using this worker: celery -A project.celery worker (using Redis as broker) and using railway platform for hosting my application but after deployment application is crashing : error is something like this : /opt/venv/lib/python3.9/site-packages/celery/platforms.py:800: RuntimeWarning: You're running the worker with superuser privileges: this is absolutely not recommended! Please specify a different user using the --uid option. User information: uid=0 euid=0 gid=0 egid=0 warnings.warn(RuntimeWarning(ROOT_DISCOURAGED.format( suggest how to run the celery process efficiently on railway. -
ModuleNotFound error (Django), i am beginner in django
It was all working when i started the server first time without startapp. after i made an application and did some modifications in the application now the server is not starting. they only changes I made in views.py and urls.py Here is the log. PS E:\CS50\files\Django\demo> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1126, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File … -
Formatting form's film with Boostrap and Django
I have a form which is generated by a model in Django made by text area, choice field, toggle field and so on like: class Test(models.Model): workerID = models.CharField(max_length=200, blank=True, null=True) dashboardURL = models.URLField(blank=True) centralinaVecchia = models.BooleanField(default=False) And I've styled the form with class StartWorker(ModelForm): class Meta: model = Test fields = ('testTitle', 'testDescription', 'centralinaVecchia') labels = { "testTitle": _("Titolo"), "testDescription": _("Descrizione"), "centralinaVecchia": _("Centralina Vecchia?"), } widgets = { 'testTitle': forms.TextInput(attrs={'class':'form-control'}), 'testDescription': forms.Textarea(attrs={'class':'form-control'}), 'centralinaVecchia': forms.CheckboxInput(attrs={'class':'form-check-input'}), The issue is that, if every single field is correctly formated one below the other, the check box is located in a weired way (see screenshot) I'm unabel to style it like the rest of the form. According to the documentation I need to add the checkbox inside a <div class="form-check"></div> but I do not know how to do it in Django -
Django - Gentella Theme
¿How can I create a new app on the django template called "Gentella"? I've tried searching and I' ve not found anything yet. Please help me!!. I know how to create a new app on django, but, the question is that when you create that app, you don' t see it on the panel in the UI of gentella. What I'm doing wrong? -
Django:Filter entries of combobox in template to foreign key
I am having trouble to find a solution to a problem of filtering entries of a combobox. Just to make it easy to understand my problem here an ERM of my models: and my Template looks like: Basicly the queryset for this template is resulting of the following code: class EquipmentinLocationAdd(CreateView): model = EquipmentInLocation form_class = EquipmentAddToLocationForm template_name = 'Procure/equipmentinlocation_add.html' def get_success_url(self): return reverse('equipmentinlocation_sys', kwargs={'pk':self.object.Institute_id}) def get_initial(self): qs = Institute.objects.get( id = self.kwargs['pk'] ) initial = {'Institute': qs} return initial Now I need to filter and restrict the entries of the combobox "Lot" only to the lots which belong to the same project as the institute. However, bringing two queries together in one template seems to be a challenge hard to solve. Need your help, please advise!!! -
Message is not sending in JavaScript WebSocket
I am trying to build a chat application using Django channels and WebSocket HTML code {% extends 'core/base.html' %} {% block title %} {{room.name}} | {% endblock %} {% block content %} <div class="p-10 lg:p-20 text-center"> <h1 class="text-5xl font-extrabold text-white drop-shadow-lg ">{{room.name}} </h1> </div> <div class="lg:w-2/4 mx-4 lg:mx-auto p-4 bg-white rounded-xl"> <div class="chat-messages space-y-3" id="chat-messages"> <div class="p-4 bg-gray-200 rounded-xl"> <p class="font-semibold">username</p> <p>lorem ipsum lolerem ipseum</p> </div> </div> </div> <div class="lg:w-2/4 mt-6 mx-4 lg:mx-auto p-4 bg-white rounded-xl"> <form action="" method="post" class="flex"> <input type="text" name="content" class="flex-1 mr-3 focus:outline-0" placeholder="Your message.." id="chat-message-input"> <button class="px-3 py-1 rounded-xl text-white bg-green-600 hover:bg-teal-700" id="chat-message-submit"> Send </button> </form> </div> {% endblock %} {% block scripts %} {{ room.slug|json_script:"json-roomname" }} {{ request.user.username|json_script:"json-username"}} <script> const roomName = JSON.parse(document.getElementById('json-roomname').textContent); const userName = JSON.parse(document.getElementById('json-username').textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/' + roomName + '/' ); chatSocket.onmessage = function(e){ console.log('onmessage') const data = JSON.parse(e.data); if (data.message){ let html = '<div class="p-4 bg-gray-200 rounded-xl">'; html += '<p class="font-semibold">' + data.username + '</p>'; html += '<p>' + data.message + '</p> </div>'; document.querySelector('#chat-messages').innerHTML += html; }else { alert('The message was empty'); } } chatSocket.onclose = function(e){ console.log('onclose') } // document.querySelector('#chat-message-submit').onclick = function(e){ e.preventDefault(); const messageInputDom = document.querySelector('#chat-message-submit'); const message = messageInputDom.value; chatSocket.send(JSON.stringify({ … -
Django Admin ForeignKey issue,
The following are my models in Django. class Authors(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) total_books = models.IntegerField(default =0) class Book(models.Model): title = models.CharField(max_length=200) topic = models.CharField(max_length=200) author = models.ForeignKey(Authors, on_delete = models.CASCADE)` I want to use Admin platform to achieve: when I add a new Book, the total_books in related author add 1. Is there any way to solve it? I would appropriate it if someone help me. Can anyone give me some ideas? -
openai.error.InvalidRequestError: This is a chat model and not supported in the v1/completions endpoint. Did you mean to use v1/chat/completions?
Hi im new to chat gpt api and im trying to make a chatbot with it. I keep getting this error when i run my code: Internal Server Error: / Traceback (most recent call last): File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\Downloads\finalproject\finalproject\django_chatbot\chatbot\views.py", line 23, in chatbot response = ask_openai(message) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\Downloads\finalproject\finalproject\django_chatbot\chatbot\views.py", line 9, in ask_openai response = openai.Completion.create( ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\api_resources\completion.py", line 25, in create return super().create(*args, **kwargs) PS C:\Users\Nathan A\Downloads\finalproject\finalproject\django_chatbot> python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 02, 2023 - 21:17:40 Django version 4.2.2, using settings 'django_chatbot.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [02/Aug/2023 21:17:42] "GET / HTTP/1.1" 200 4265 Internal Server Error: / Traceback (most recent call last): File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\Downloads\finalproject\finalproject\django_chatbot\chatbot\views.py", line 23, in chatbot response = ask_openai(message) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\Downloads\finalproject\finalproject\django_chatbot\chatbot\views.py", line 9, in ask_openai response = openai.Completion.create( ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\api_resources\completion.py", line … -
How to handle NULL for Django DB Function Concat?
I want the query set to return concatenated string for address. I'm currently writing code like this: queryset = Place.objects.annotate( place_address= Concat('address__city', Value(', '),'address__state__name')) ) It return fine when city and state field is not empty. But it does not handle null value with this solution where the result could ended up: "Kuala Lumpur, " OR ", Selangor" OR ", " Is there a way to skip adding delimiter when the field in front is null? Thanks. -
Hide HTMX search results after option is selected
I have a search bar I created using HTMX and django forms that displays results correctly. I have a javascript selectOption() function filling the search bar with whatever the selected option is, but I am having trouble with the search results not going away after I select an option. Can this be handled through javascipt? Additionally, the search bar returns random results once I type something and then delete it, leaving it blank. Is there something I could fill into hx-trigger to fix this issue? See htmx tags below widget_attrs_nha_autosearch = { 'class': 'form-control', 'data-user-entry': 1, 'disabled': value.get('read_only'), 'hx-post': reverse('ng_django_pmp:nha-autosearch'), 'hx-target': '#results', 'hx-trigger': "keyup changed delay:500ms, search" } See search-results html below {% if results %} <ul class="list-group col-xs-12"> {% for part in results %} <li class="list-group-item d-flex justify-content-between align-items-center" onclick="selectOption('{{ part.manufacturer_part_number }}')">{{ part.manufacturer_part_number }}</li> {% endfor %} </ul> {% else %} <p>No search results</p> {% endif %} <script defer> function selectOption (partNumber) { const input = document.querySelector('#id_nha_override'); input.value = partNumber; } -
Django LIKE operation
I'm trying to send a query through Django python I also try to block any sql injection exploits Can someone explain to me how messaging is done LIKE Query for example "SELECT * FROM admin WHERE name LIKE '%myTitle%' It's easy to configure Query like this cursor.execute("SELECT * FROM admin WHERE name= %s", (_id, )); But when inserting %s Many errors are made when canceling %% From the text, for example SELECT * FROM admin WHERE name LIKE %s When Query Done it be like SELECT * FROM admin WHERE name 'MyTitle' It is being implemented correctly, but I want it to be set %% among %s LIKE SELECT * FROM admin WHERE name '%MyTitle%' Can someone explain to me how to solve this problem my Simple Script from django.db import connection title = "myTitle" query = "SELECT * FROM admin WHERE name LIKE %s" with connection.cursor() as cursor: cursor.execute(query, (title,)) -
How to Deploy a Django App to AWS Amplify using GitHub
I am trying to find a step-by-step guide that would detail the deployment of a django application using aws amplify. Although options like AWS ec2 are available, I would also like to see if a django web app deployment is possible on AWS Amplify. I have found numerous videos and posts on NextJS developers switching over to AWS Amplify as usage fees on Vercel are getting astronomically higher after a certain amount. Would like to ask for any leads to a guide that would deploy a django app on AWS Amplify. Thank you! <3 -
Nginx throws 403 Forbidden eror whenserving js and css files
I am trying to deploy a django project on an ec2 instance wuth gunicron and nginx and keep getting 403 errors when trying to setup with nginx. When I run the server using python3 manage.py runserver 0.0.0.0:8000 everything is served correctly and my static files are served but when I use nginx it stops serving my static files and throws a 403 error. /etc/nginx/sites-available/djangoproj server { listen 80; server_name X.XXX.XXX.XXX; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/djangoproj; } location / { include /etc/nginx/mime.types; include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Also when I make changes I then restart with sudo systemctl daemon-reload and sudo systemctl restart gunicorn. This is my first attempt at deploying a website so Im still a bit new when it comes to working with a linux server. I double checked the owner of the public directory and its set to www-data and all the static directories have read and write permissions (-rw-r--r-- 1 ubuntu ubuntu 2358255 Aug 2 18:16 main.js) so I dont think it has to do with permissions. Also I included my nginx for extra context. /etc/nginx/nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections … -
Django Mail isnt sending anymore
I used to have a working system where all mails got delivered and everything worked. I didnt change nothing but now the Mails arent sending anymore. I checked the mail connection on another server and the same data still works and gets send. Do I have an outdated version or something? How can I fix this? This is my settings.py DEFAULT_FROM_EMAIL='email@here.com' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.myemailprovider.com' EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_USE_TLS = False EMAIL_HOST_USER = 'mymail@mail.com' EMAIL_HOST_PASSWORD = 'MyPassword124' views.py send_mail( 'Test title', 'Test Email.', '', ['my@mail.com'], fail_silently=False, ) I am currently running a gunicorn server on nginx. -
Docker Compose: How to prevent db volume being cleared every time a container is build
I have dockerfile and compose file set up that works perfectly fine, that runs multiple service. But my problem is every time I do file changes deploy and re-build the containers to apply new changes; my postgres db volume is being recreated hence re-running migrations loosing existing data. Dockerfile # pull official base image FROM python:3.9.6-alpine as builder # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV CRYPTOGRAPHY_DONT_BUILD_RUST=1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev RUN apk add --no-cache \ libressl-dev \ musl-dev \ libffi-dev RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add jpeg-dev zlib-dev make libjpeg \ && apk del build-deps # lint RUN pip install --upgrade pip # install dependencies COPY requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt RUN apk del \ libressl-dev \ musl-dev \ libffi-dev ######### # FINAL # ######### # pull official base image FROM python:3.9.6-alpine as runner # create the app user RUN addgroup -S app && adduser -S app -G app # create the appropriate directories ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $APP_HOME RUN mkdir … -
In Django, how to multiply-aggregate a field?
I want to aggregate a field using multiplication, but apparently Django doesn't have a Product function among its aggregation function. Example of what I want to do # models.py class MyModel(models.Model): ratio = models.DecimalField(...) # views.py mys = MyModel.objects.filter(...).aggregate(cum_ratio=Product(ratio)) How to achieve this? I feel like since Django didn't include a Product function like they did with Sum suggests that it's trivial but I can't put my finger on it. -
OperationalError at /admin/ no such table: django_session
I encountered a problem in my Django project, which I thought was from the database, but when I deleted it and entered the command python.exe .\manage.py makemigrations and python manage.py migrate, but when the command python manage.py migrate, everything went well except for one thing the problem: Operations to perform: Apply all migrations: account, admin, auth, blog, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying account.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying auth.0012_alter_user_first_name_max_length... OK Applying auth.0013_remove_user_id_alter_user_username...Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 87, in _execute return self.cursor.execute(sql) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\sqlite3\base.py", line 324, in execute return super().execute(query) ^^^^^^^^^^^^^^^^^^^^^^ sqlite3.OperationalError: foreign key mismatch - "auth_user_groups" referencing "auth_user" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\user\Desktop\shop\manage.py", line 22, in <module> main() File "C:\Users\user\Desktop\shop\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File … -
Django: How to create custom ModelSerializer from multiple models/tables in mySQL database?
I'm working on a Django project with an already existing mySQL database. I've quickly learned that mySQL lacks the explicit relationships found in postgresSQL databases where you can establish one to one, one to many, many to many relationships. Instead, you typically need to create a whole other table just for relationships. So currently, I have three tables: userpie_users, radar_sites, and userpie_users2radars (table describing the relationships). Table: userpie_users Table: radar_sites Table: userpie_users2radars Just to clarify, let's examine the first row of userpie_users2radars: id: 2, user_id: 78, radar_id: 17 The id: 2 can be ignored but this row specifies that user_id (78) from userpie_users is attached to radar_id(17) from radar_sites. The next row reveals that the same user also is attached to radar_id(4). For my API "GET" endpoint (http://127.0.0.1:8000/api/map/user_id), I want my final JSON body response to be something like this: { "user_id":"123", "last_name":"smith", "first_name":"john", "last_radar":"28", "radars":[["19","Coal Point Reserve UCSB"],["39","Harvey"],["33","Hawaii"]] } The first four fields are in the userpie_users table so this can be easily serialized with ModelSerializer. "last_radar" is cut off in the screenshot but it's there. "radars" however is an array I need to make by grabbing the user_id from the url parameters, looking through each row in userpie_users2radars … -
Django website not working as expected on home url, but eventually works upon consistent retry
so I have this single page application that runs django backend here. It actually has 4 header option: Jobs (the default), competitions, learn, about. When you visit the application, sometimes it fails to load the jobs section. The spinner just keeps spinning, and when you check the console, you will see an error that says VM96:2 Uncaught (in promise) SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON Now this is very confusing to me because if you keep clicking the Jobs link, it will eventually load the jobs page correctly (or you can keep trying a complete reload of the url, it will eventually load properly). However, the other hyperlinks work. This problem only happens on the job page, which is the homepage nginx configuration server { server_name pythonyard.com www.pythonyard.com *.pythonyard.com; location /static/ { alias /home/kenechukwu_webapp/allpython/backend/static/; } location / { try_files $uri @node; } location @node { proxy_pass http://127.0.0.1:8000; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/pythonyard.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/pythonyard.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.pythonyard.com) { return 301 https://$host$request_uri; } # managed by Certbot if … -
django-filter using filter class in another filter class
I use django-filter I have two models named Person and Member. Person has been defined as foreign key in Member. As an example here, I added less fields, normally the PersonModel model has a lot more fields. What I want to do here is to use all the filter fields I created for person in the filter class I created for Member. models.py class PersonModel(models.Model): name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class MemberModel(models.Model) register_no = models.CharField(max_length=20, unique=True) person = filters.ForeignKey(PersonModel, on_delete=models.PROTECT, related_name='members') filters.py class PersonFilter(filters.FilterSet): name= filters.CharFilter(field_name='name') last_name= filters.CharFilter(field_name='last_name') class MemberFilter(filters.FilterSet): register_no = filters.CharFilter(field_name='register_no') # # I want to use PersonFilter here # for example: person = PersonFilter(lookup_expr="person") or how? # # I don't want to do it this way: # person_name = filters.CharFilter(field_name='person__name') # person_last_name = filters.CharFilter(field_name='person__last_name') -
How to convert Figma design to Django?
I am making an app using Django and Python and I want to integrate some Figma designs with my web application. Does anyone know how to do this? -
Deploying Django on Heroku smart-open Causing Failure
Trying to deploy Django project to Heroku I get the following error: python setup.py egg_info did not run successfully. exit code: 1 error in smart_open setup command: 'python_requires' must be a string containing valid version specifiers; Invalid specifier: '>=3.6.*' note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed Tried multiple versions of smart-open and tried removing it from requirements.txt, the invalid specifier is NOT in my requirements.txt (this is: smart-open==4.1.0) or I have tried multiple other versions, all break the build. I’ve tried changing setup tools on Heroku to eg setuptools==40.3.0, no dice (same errors). -
Django app not loading with DisallowedHost error even after adding IP to ALLOWED_HOSTS
I'm facing an issue with my Django web application deployment on an Amazon EC2 instance. The app is running using Gunicorn and Nginx as a reverse proxy. However, when I try to access the app using the public IP address (ipaddress:8000), it's not loading, and I keep getting a "DisallowedHost" error. Here are the steps I've taken so far: In my Django settings.py, I've added the public IP address to the ALLOWED_HOSTS setting: python Copy code ALLOWED_HOSTS = ['ipaddress:8000'] I've confirmed that Gunicorn is running and bound to ipaddress:8000 . Nginx is configured as a reverse proxy with the following settings: nginx Copy code server { listen 80; server_name ipaddress:8000 location / { proxy_pass http://ipaddress:8000 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } Despite these configurations, the app still does not load, and I receive the following error in my Django logs: css Copy code [2023-08-02 17:28:00 +0000] [#] [INFO] Starting gunicorn 21.2.0 [2023-08-02 17:28:00 +0000] [#] [INFO] Listening at: http://ipaddress:8000 (#) ... DisallowedHost at / Invalid HTTP_HOST header: 'ip address'. You may need to add 'ipaddress' to ALLOWED_HOSTS. It seems like Django is still considering the request host as 'ipaddress', even though I've explicitly added it to ALLOWED_HOSTS. Any …