Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot connect MySQL in a Django project docker container
First, I installed Docker v4.20.1 in my Windows 10. I run docker compose successfully and their status are as the following screenshot. my phpmyadmin container can access mysql db successfully as the following screenshot. If I run the django project in my host computer(Windows 10), it also connect mysql db successfully. But If I try to run the django server in the web container, it shows up the error message that it can't connect mysql db correctly. The error logs: root@80c6e906cf7e:/usr/src/app# python caravan/manage.py migrate Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/mysql/connector/connection_cext.py", line 291, in _open_connection self._cmysql.connect(**cnx_kwargs) _mysql_connector.MySQLInterfaceError: Can't connect to MySQL server on '127.0.0.1:3306' (111) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/usr/local/lib/python3.10/dist-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/django/db/backends/base/base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.10/dist-packages/mysql/connector/django/base.py", line 399, in get_new_connection cnx = mysql.connector.connect(**conn_params) File "/usr/local/lib/python3.10/dist-packages/mysql/connector/pooling.py", line 293, in connect return CMySQLConnection(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/mysql/connector/connection_cext.py", line 120, in __init__ self.connect(**kwargs) File "/usr/local/lib/python3.10/dist-packages/mysql/connector/abstracts.py", line 1181, in connect self._open_connection() File "/usr/local/lib/python3.10/dist-packages/mysql/connector/connection_cext.py", line 296, in _open_connection raise get_mysql_exception( mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on '127.0.0.1:3306' (111) The above exception … -
Celery not running new task
I've readded an old Celery task to my Django app running on Heroku, but it's not being run by the worker. The task appears in the tasks when the worker starts, and I can see the scheduler sending it to the worker. However, it is never received by the worker. What can I do to troubleshoot this issue? Other tasks added are running fine and it runs fine on the staging server which is another instance on Heroku. I've tried restarting all the dynos and changing the name of the task and repushing it but that hasn't worked. -
Unable to understand the bug in views.py
This is my views.py in which I have created the class Pizza. from django.shortcuts import render from .models import Pizza def index(request): pizzas = Pizza.objects.all() return render(request, 'menu/index.html', {'pizzas ':pizzas}) And this is the html file: <html lang="en"> <head> <meta charset="UTF-8"> <title>Our Pizzas</title> </head> <body> <h1>Our Pizzas</h1> <ul> {% for pizza in pizzas %} <li>{{pizza.name}}</li> {% endfor %} </ul> </body> </html> In the result the page should have given me the names of pizzas stored in the class pizza but it is giving me only what is inside <h1></h1> This is what I get When I inspect the html page it gives me this: enter image description here There is nothing between the <ul></ul> When I run the debugger for the views.py file, it gives me: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Please suggest solution -
How do I add custom attributes autocomplete to crispy_forms Django
I would like to check how do I add the autocomplete attribute to the crispy_forms. Any help would be appreciated. Thanks. -
How to filter model by foreign key field of FK field?
I have model 'Employee': class Employee(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) lastname = models.CharField(max_length=50) end_user_id = models.CharField(max_length=8, help_text=u"Please enter the end user id, like ABC1WZ1") history = HistoricalRecords() def __str__(self): return self.name + ' ' + self.lastname Employee can be a manager, so I also have model 'Manager': class Manager(models.Model): id = models.AutoField(primary_key=True) manager = models.ForeignKey(Employee, verbose_name='manager', on_delete = models.DO_NOTHING) def __str__(self): return self.manager .name + ' ' + self.manager .lastname And my main model 'MissForm': class MissForm(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) auto_inc_id = models.IntegerField(blank=True, null=True) sender = models.ForeignKey(Employee, verbose_name='sender', on_delete = models.DO_NOTHING, blank=True, null=True) manager = models.ForeignKey(Manager, verbose_name='Manager', on_delete = models.DO_NOTHING, related_name='+', blank=True, null=True ) status_flag = models.PositiveIntegerField(default=1) I am trying to get all instances of MissForm model where manager is a current logined user and status_flag=2( in views.py): login_user_id = request.user.username.upper() # returns smth like ABC1WZ1 forms = MissForm.objects.filter(status_flag=2, manager__manager__end_user_id=login_user_id) But it doesn't work. What I am doing wrong? -
How to display views.py results directly and dynamically on template.html in django?
I have a django website project with exper.html template and views.py as processing backend. I want when we enter parameters or input in the textarea and after that press the submit button, then views.py can process those parameters and generate images and display them directly in the exper.html template file. below is the code for expert.html and views.py exper.html: <div class="container-area text-center"> <form id="myForm" class="row"> {% csrf_token %} <div class="col-md-12"> <label for="input_text"></label><br> <textarea id="input_text" name="input_text" rows="10" cols="100" placeholder="Write Code Here" required></textarea><br><br> </div> <div class="col-md-12 d-flex justify-content-center align-items-center"> <input type="button" value="Run" onclick="submitForm()"> </div> </form> </div> <script> function submitForm() { const form = document.getElementById('myForm'); const csrfToken = document.getElementsByName('csrfmiddlewaretoken')[0].value; const inputText = document.getElementById('input_text').value; const xhr = new XMLHttpRequest(); xhr.open('POST', ''); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.setRequestHeader('X-CSRFToken', csrfToken); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { const response = JSON.parse(xhr.responseText); displayImages(response.data_input_img, response.qam_mod_img); } }; xhr.send('input_text=' + encodeURIComponent(inputText)); } </script> views.py def exper(request): if request.method == 'POST': form = ParameterForm(request.POST) if form.is_valid(): input_text = form.cleaned_data['input_text'] subcarrier = 0 mod_order = 0 for param in input_text.split(): if param.startswith('subcarrier='): subcarrier = int(param.split('=')[1]) elif param.startswith('mod_order='): mod_order = int(param.split('=')[1]) data_in = generate_input_data(subcarrier, mod_order) plt.figure() plt.stem(data_in, use_line_collection=True) plt.title('Data Input') plt.xlabel('Indeks Data') plt.ylabel('Nilai Data') plt.grid(True) plt.savefig('static/files/datainput.png') data_input_img_base64 = … -
prefetch_related() without specifying lookups
I encountered such a queryset in a project : qs.prefetch_related().other().methods() Is there a point having such call to prefetch_related() method without specifying any lookup? -
Django - [wsgi:error] [pid 16542:tid 140650901133056] Truncated or oversized response headers received from daemon process
I have googled and tried each and every option but nothing worked . Below are the version specification which is used . Apache/2.4.37 (AlmaLinux) OpenSSL/1.1.1k mod_wsgi/4.6.4 Python/3.6 and mariadb as the database Using Virtual environment Below are my Virtual Configuration paramters with wsgi WSGIDaemonProcess cosmos processes=6 maximum-requests=300 header-buffer-size=65536 connect-timeout=30 python-path=/opt/cosmos/cosmos_api_v3:/opt/cosmos/cosmosenv/lib/python3.6/site-packages/ WSGIApplicationGroup %{GLOBAL} WSGIProcessGroup cosmos WSGIScriptAlias /api /opt/cosmos/cosmos_api_v3/cosmos/wsgi.py WSGIPassAuthorization On Below are installed python packages Package Version amqp 5.0.6 ansible 2.9.0 asgiref 3.4.1 bcrypt 3.2.0 beautifulsoup4 4.11.2 billiard 3.6.4.0 cached-property 1.5.2 celery 5.1.2 certifi 2021.5.30 cffi 1.15.0 charset-normalizer 2.0.6 click 7.1.2 click-didyoumean 0.3.0 click-plugins 1.1.1 click-repl 0.2.0 coreapi 2.3.3 coreschema 0.0.4 crypto 1.4.1 cryptography 35.0.0 Django 3.2.7 django-auth-ldap 3.0.0 django-celery-beat 2.2.1 django-celery-results 2.2.0 django-cors-headers 3.10.0 django-filter 21.1 django-rest-swagger 2.2.0 django-timezone-field 4.2.1 djangorestframework 3.12.4 djangorestframework-jwt 1.11.0 djangorestframework-simplejwt 4.4.0 docopt 0.6.2 humanfriendly 10.0 idna 3.2 importlib-metadata 4.8.1 itypes 1.2.0 Jinja2 3.0.2 kombu 5.1.0 lxml 4.6.3 MarkupSafe 2.0.1 mysql-connector 2.2.9 Naked 0.1.31 openapi-codec 1.3.2 packaging 21.0 pandas 1.1.5 paramiko 2.8.0 pip 21.3.1 prompt-toolkit 3.0.20 pyasn1 0.4.8 pyasn1-modules 0.2.8 pycparser 2.20 pycryptodome 3.11.0 pyflakes 2.3.1 Pygments 2.10.0 PyJWT 1.7.1 PyMySQL 1.0.2 PyNaCl 1.4.0 pyparsing 3.0.2 python-crontab 2.5.1 python-dateutil 2.8.2 python-dotenv 0.19.2 python-ldap 3.3.1 python-magic 0.4.27 pytz 2021.1 pyvcloud 23.0.3 pyvim 3.0.2 pyvmomi 7.0.2 PyYAML 6.0 … -
I am unable to obtain list of elements from a class created in a python file to display in an HTML file
This is my views.py in which I have created the class Pizza. from django.shortcuts import render from .models import Pizza def index(request): pizzas = Pizza.objects.all() return render(request, 'menu/index.html', {'pizzas ': pizzas}) And this is the html file: <html lang="en"> <head> <meta charset="UTF-8"> <title>Our Pizzas</title> </head> <body> <h1>Our Pizzas</h1> <ul> {% for pizza in pizzas %} <li>{{pizza.name}}</li> {% endfor %} </ul> </body> </html> In the result the page should have given me the names of pizzas stored in the class pizza but it is giving me only what is inside and tags. This is what I get When I inspect the html page it gives me this: enter image description here There is nothing between the and tags. Maybe it is unable to access elements from the class. Please help. -
Authenticating queries in Django Graphene custom nodes with filters and connections?
I'm working on a Django project using Graphene for GraphQL API implementation. I have a custom node called PoemNode which extends DjangoObjectType. I want to authenticate queries made to this node and also include filtering and pagination capabilities using filterset_class and connection_class respectively. I have already set up the authentication backend in Django and have the necessary packages installed. However, I'm unsure how to integrate the authentication logic into my custom node and how to use the filterset_class and connection_class for querying. class PoemNode(DjangoObjectType): class Meta: model = Poem interfaces = (Node,) filterset_class = PoemFilter connection_class = CountableConnectionBase Can anyone guide me on how to authenticate queries for the PoemNode and utilize the filterset_class and connection_class for querying with filtering and pagination capabilities? Thank you in advance for your help! -
how do i convert this query to django orm?
i have a query, how do i convert this query to django orm? SELECT tem.urutan,tem.rentang AS lama_kerja, count(*) as jumlah FROM ( SELECT CASE WHEN employee_join_date IS NULL THEN '1' WHEN EXTRACT(YEAR FROM age(date(now()), employee_join_date)) < 1 THEN '2' WHEN 1 <= EXTRACT(YEAR FROM age(date(now()), employee_join_date)) AND EXTRACT(YEAR FROM age(date(now()), employee_join_date)) <= 10 THEN '3' WHEN 11 <= EXTRACT(YEAR FROM age(date(now()), employee_join_date)) AND EXTRACT(YEAR FROM age(date(now()), employee_join_date)) <= 20 THEN '4' WHEN EXTRACT(YEAR FROM age(date(now()), employee_join_date)) >= 21 THEN '5' ELSE '0' END AS urutan, CASE WHEN employee_join_date IS NULL THEN '<>' WHEN EXTRACT(YEAR FROM age(date(now()), employee_join_date)) < 1 THEN '< 1 Tahun' WHEN 1 <= EXTRACT(YEAR FROM age(date(now()), employee_join_date)) AND EXTRACT(YEAR FROM age(date(now()), employee_join_date)) <= 10 THEN '1 - 10 Tahun' WHEN 11 <= EXTRACT(YEAR FROM age(date(now()), employee_join_date)) AND EXTRACT(YEAR FROM age(date(now()), employee_join_date)) <= 20 THEN '11 - 20 Tahun' WHEN EXTRACT(YEAR FROM age(date(now()), employee_join_date)) >= 21 THEN '> 21 Tahun' ELSE 'Terdefinisi' END AS rentang FROM employees WHERE (employee_resign_date Is Null OR employee_resign_date > date(now())) AND employee_is_resign = '2' ) AS tem GROUP BY tem.urutan,tem.rentang ORDER BY tem.urutan result to this or json enter image description here -
Increase Django CSRF tocken longevity
I get lots of Django CSRF errors due to timeout. In normal operations, the form submissions are OK. But, if I leave the page for a few hours and then submit it, it will fails with the Forbidden (403) CSRF verification failed. Request aborted screen. To overcome this issue, I added the following line to the settings.py : SESSION_COOKIE_AGE = 604800 # one week But a few hours leading to timeout means that this line has had no effect. I need CSRF tokens longevity be increased to a few days rather than minutes. How to achieve this? -
Celery beat_scheduler's task executed but not registered in model django_celery_beat_periodictask
I am trying basic implementation of celery worker and celery beat on the windows PC. The celery beat is sending the task successfully and the celery worker received the task from celery beat and executed the task. The problem is there is no task registered in django_celery_beat_periodictask as expected. Problem: Why there are no task in django_celery_beat_periodictask? Addon questions: If there are no task in django_celery_beat_periodictask then how does the celery beat executing the task? What are the another data sources where celery worker took the task? Project Tree celery_with_django |- django_celery_project |- __init__.py |- settings.py |- celery.py other files |- mainapp |- tasks.py other files |- requirements.txt Command to run the code django server: python manage.py runserver celery worker: celery -A django_celery_project.celery worker --pool=solo -l info **# (without --pool=solo the terminal is hard to interrupt) celery beat: celery -A django_celery_project beat -l info My code look like this requirements.py amqp==5.1.1 asgiref==3.7.2 async-timeout==4.0.2 billiard==3.6.4.0 celery==5.2.7 click==8.1.3 click-didyoumean==0.3.0 click-plugins==1.1.1 click-repl==0.2.0 colorama==0.4.6 cron-descriptor==1.4.0 Django==4.2.1 django-celery-beat==2.5.0 django-celery-results==2.5.1 django-timezone-field==5.1 kombu==5.2.4 prompt-toolkit==3.0.38 python-crontab==2.7.1 python-dateutil==2.8.2 pytz==2023.3 redis==4.5.5 six==1.16.0 sqlparse==0.4.4 typing_extensions==4.6.3 tzdata==2023.3 vine==5.0.0 wcwidth==0.2.6 django_celery_project/init.py from .celery import app as celery_app __all__ = ('celery_app',) django_celery_project/settings.py **# other settings **# CELERY SETTINGS CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_RESULT_BACKEND = 'django-db' … -
Django Celery running a function multiple times?
In Django, I have created an app for sending emails to clients. I am using Celery Beat to schedule a daily task that executes the schedule_emails function at 12:30 AM. This function runs perfectly. However, I am encountering a problem where the send_email function is running multiple times and sending duplicate emails to specific clients from my email account at the same time. I have checked the logs of the celery worker it shows that a particular task_id was received multiple times and succeed succeeded multiple times. I am using the supervisor to run celery and celery_beat services in the background. settings.py # Celery Settings CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_TASK_ACKS_LATE = True CELERY_RESULT_BACKEND = 'django-db' CELERY_BEAT_SCHEDULE_FILENAME = '.celery/beat-schedule' CELERYD_LOG_FILE = '.celery/celery.log' CELERYBEAT_LOG_FILE = '.celery/celerybeat.log' CELERY_BEAT_SCHEDULE = { 'schedule_emails': { 'task': 'myapp.tasks.schedule_emails', 'schedule': crontab(hour=0, minute=30), }, } celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings from decouple import config if config('ENVIRONMENT') == 'development': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyProject.settings.development') else: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyProject.settings.production') app = Celery('MyProject**strong text**') app.conf.enable_utc = False app.conf.update(timezone='Asia/Kolkata') app.config_from_object(settings, namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request : {self.request!r}') task.py from celery import shared_task @shared_task def … -
Is it possible to use functions like gettext() inside Formatted String Literals (F-Strings)
So, is it possible to call a function inside Formatted String Literals (F-String) ? ex: from django.utils.translation import gettext_lazy as _ def func(x): return f'{_("Value")}: {x}' print(func(4)) -
Django Q: build dynamic query from array
For a Django project, I have a dictionary which contains the model name and the columns where to look for. So what I want to achieve is to build the query from the variables coming from my dictionary. sq = [] for x in columns: print(x) sq.append(f'Q({x}__icontains=val)') print(sq) query = (' | '.join(sq)) print(query) lookups = Q(name__icontains=val) | Q(code__icontains=val) # lookups = query When I do the above, it correctly builds the "string" representing the query, but I'm unable to use it. The error is as follows: Traceback (most recent call last): File "/home/user/price_engine/env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/user/price_engine/env/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/price_engine/masterdata/views.py", line 50, in search_form results = Plant.objects.filter(query).distinct() File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/query.py", line 1436, in filter return self._filter_or_exclude(False, args, kwargs) File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/query.py", line 1454, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/query.py", line 1461, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1534, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1565, in _add_q child_clause, needed_inner = self.build_filter( File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1412, in build_filter arg, value = filter_expr ValueError: too many values to unpack (expected 2) [05/Jul/2023 04:27:27] "POST … -
How to use a background task but i want it to send it using render to specific url
I try to render but it should put request using parameter, how to handle the request when using the background task in django @background(schedule=60) # Runs every 60 seconds def auto_check_status (request): current_time = timezone.now() time_threshold = current_time - timedelta(minutes=10) try: transactions = Transaction.objects.filter( Q(trx_status='PENDING') | Q(trx_status='SUBMITTED'), trx_type_id='R', trx_time__lt=time_threshold ).order_by('trx_time') for transaction in transactions: # Perform actions on each transaction store_database(transaction) message = createrequest(transaction) message = construct_source_string_and_sign(message) npg_url = f"{settings.NPG_URL}/in" npg_url = f"{settings.NPG_URL}/in" return render(request, 'transactions/bayar.html', {'trx': message, 'npg_url' :npg_url}) except Exception as e: print(str(e)) -
Arabic translations not displayed correctly in Django/Celery notification system
I'm currently working on a Django application that includes various functionalities, including notification delivery, in multiple languages. While most of the application works well with Arabic and other languages, I'm facing an issue with Arabic translations in certain parts of the application, including notifications. The Arabic translations are not being displayed correctly, while translations in other languages, such as English and French, work without any issues. Here are the details of my setup: The application uses Django and Celery for task management and background processing. I have added Arabic translations for different text elements in the respective translation files. The Arabic translations work fine in most parts of the application, including UI labels and content. However, when it comes to notifications, specifically in Arabic, the translations are not displayed correctly. Other functionalities, such as database operations, user management, and data processing, work as expected with the Arabic translations. I have ensured that the necessary translations are present, and the language preferences are correctly set for affected users. The issue seems to be specific to the notification tasks triggered by certain actions or events. It's puzzling because the Arabic translations work well in other areas of the application. I would greatly … -
How to connect 2 views in the same Django app? (ListView and EditView)
I have 2 apps called Prospecto(which means Prospect) and Cliente(which means Customer). When you see a register in EditView and click on its checkbox, you can indicate whether the register is still in Prospecto or Cliente If you don't click on the checkbox, that record is still in the Propsecto If you click the checkbox, that record becomes a Cliente and is no longer a Prospect In the code I did, when I clicked the checkbox, it turns into record in Customer(that's ok), but I can't delete it from Prospecto(in ProspectoListView). **views.py class ProspectoListView(ListView): model = Prospecto template_name = 'prospectos.html' context_object_name = 'prospectos' def get_queryset(self): queryset = super().get_queryset() fecha_inicio = self.request.GET.get('fecha_inicio') fecha_fin = self.request.GET.get('fecha_fin') if fecha_inicio and fecha_fin: queryset = queryset.filter(fecha__range=[fecha_inicio, fecha_fin]) elif fecha_inicio: queryset = queryset.filter(fecha__gte=fecha_inicio) elif fecha_fin: queryset = queryset.filter(fecha__lte=fecha_fin) return queryset def ProspectoEditar(request, pk): prospecto = get_object_or_404(Prospecto, pk=pk) if request.method == 'POST': form = ProspectoForm(request.POST, instance=prospecto) if 'es_cliente' in request.POST: cliente = Cliente(nombre=prospecto.nombre) cliente.save() prospecto.es_cliente = True prospecto.delete() if form.is_valid(): form.save() return redirect('prospectos:prospectos_list') else: form = ProspectoForm(instance=prospecto) return render(request, 'prospectos-editar.html', {'form': form}) I try with this solution, adding delete() but it doesn't work class ProspectoListView(ListView): model = Prospecto template_name = 'prospectos.html' context_object_name = 'prospectos' def get_queryset(self): fecha_inicio … -
Failed to join room. Token authentication error
I am working on a django project in which I have used zeegocloud uikits for one-one video calling web application. Even when I am using the downloadable uikits html file provided by zeegocloud itself, in which it has generated token using appID, userID, serversecret, username, but then also token authentication error is coming. I am unable to solve this issue -
Docker Compose Up - Received Permission Denied
I am unable to start a new django/python app with docker. I received permission denied. I recently bought a new computer and my app I had previously used with docker is working fine. I then recently tried to build a flask/carmen app but deleted everything that I had loaded. Im not sure if that is effecting my docker containers but my previous app will still do docker compose up and down. I tried this weekly-finances docker-compose config name: weekly-finances services: web: build: context: /Users/eleahburman/Desktop/code/weekly-finances dockerfile: Dockerfile command: - python - manage.py - runserver - 0.0.0.0:3000 networks: default: null ports: - mode: ingress target: 3000 published: "3000" protocol: tcp volumes: - type: bind source: /Users/eleahburman/Desktop/code/weekly-finances target: /code bind: create_host_path: true networks: default: name: weekly-finances_default and the docker compose seems correct. Here is my yaml file: services: web: build: . command: python manage.py runserver 0.0.0.0:3000 volumes: - .:/code ports: - "3000:3000" and here is my docker file: syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ I tried deleting every app I had by docker and then cloning and adding an env. I started over my new app. I tried deleting … -
I have no clue what's going on
I just got to finishing a tutorial with the following link: https://www.youtube.com/watch?v=eOVLhM6_6t0&t=572s and the last step is to check that the server is running properly using python manage.py runserver however when I try to do this, the usual error pops up: [Errno 2] No such file or directory which I was able to solve with the absoulte path solutions provided online. However my problem is not that the problem comes when I finally reach the right cd to be in and all of this errors appear in the terminal: https://docs.google.com/document/d/1PJB2rRQ-Lyd8GQd3Hl9krkTlHD9C60WeakNk-9tM5y0/edit It was so long I couldn't even copy it all here without the computer bugging I have no clue what even is going on here or how could I solve it. I've been stuck here for the past hour. Thanks for the help. -
404 Not Found nginx/1.18.0 (Ubuntu) on running django rest framework with EC2 along with gunicorn, nginx and Supervisor
So I hosted my django rest framework project on AWS EC2. I integrated nginx, gunicorn and Supervisor along with it. After it shows successful configuration, the only link that works is the default one. Example http://35.154.109.114/ works but any other URL say http://35.154.109.114/test isn't working How ever these links work when I use a standard gunicorn --bind 0.0.0.0:8000 DemoProject.wsgi:application command. Please let me know how to work this out. -
Django passing a string from one view to another
I have one view with a chatbot on it, and it works fine. I added a second view and registered it in the urls.py file and simply passed the chatbot response to the new function to display and I got a 500 error. The code from my views.py, urls.py, main.html, and main_2.html pages is posted below. What am I missing? Thanks in advance. VIEWS.PY ` from django.shortcuts import render import openai, os from dotenv import load_dotenv from django.http import HttpResponse load_dotenv() api_key = os.getenv("OPENAI_KEY", None) def chatbot(request): chatbot_response = None if api_key is not None and request.method == 'POST': openai.api_key = api_key user_input = request.POST.get('user_input') prompt = user_input response = openai.Completion.create( engine = 'text-davinci-003', prompt = prompt, max_tokens=256, # stop="." temperature=0.5 ) print(response) chatbot_response = response["choices"][0]["text"] sayhi(request, chatbot_response) <-----(The error comes from this line. When I comment this out it works fine return render(request, 'main.html',{"response": chatbot_response}) def sayhi(request, chat_out): #return HttpResponse("hi") return render(request, 'main_2.html',{"response": chat_out}) URLS.PY (located in the parent directory of the views.py file) urlpatterns = [ path("", chatbot, name="chatbot"), # Uncomment this and the entry in `INSTALLED_APPS` if you wish to use the Django admin feature: # https://docs.djangoproject.com/en/4.2/ref/contrib/admin/ # path("admin/", admin.site.urls), path("sayhi", sayhi) ] MAIN.HTML {% extends 'base.html' … -
Link from Django Model's "absolute url" to its admin page
According to the docs, you can specify a get_absolute_url in your Django Model for a "View on site" button to show up on Django Admin. However, how would you do the opposite? A link on the above defined "absolute url" that takes you to the admin page for that instance? I can think of ways to hardcode the admin url and fill in just the instance ID, but I was hoping for a pythonic way (e.g. instance.get_admin_url()) Thanks for the help!