Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does anyone know what cause this following error: (I use vercel to deploy my django code online)
error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully.│ exit code: 1╰─> [35 lines of output]/tmp/pip-build-env-l6u27ub6/overlay/lib/python3.9/site-packages/setuptools/config/setupcfg.py:293: _DeprecatedConfig: Deprecated config in setup.cfg!! \\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\* The license_file parameter is deprecated, use license_files instead. By 2023-Oct-30, you need to update your project and remove deprecated calls or your builds will no longer be supported. See https://setuptools.pypa.io/en/latest/userguide/declarative_config.html for details. \\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\* !!parsed = self.parsers.get(option_name, lambda x: x)(value)running egg_infowriting psycopg2.egg-info/PKG-INFOwriting dependency_links to psycopg2.egg-info/dependency_links.txtwriting top-level names to psycopg2.egg-info/top_level.txt Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directorycontaining pg_config to the $PATH or specify the full executable path with theoption: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at<https://www.psycopg.org/docs/install.html\>). [end of output] note: This error originates from a subprocess, and is likely not a problem with pip.error: subprocess-exited-with-error note: This error originates from a subprocess, and is likely not a problem with pip.Traceback (most recent call last):File "/vercel/path0/manage.py", line 11, in mainfrom django.core.management import execute_from_command_lineModuleNotFoundError: No module named 'django'The above exception was the direct cause of the following … -
'Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)
Im using a 3rd party api service for a text sending job. When I send around 5000 numbers as payload to the API, it works fine. I have noticed that sometimes when the payload count exceeds to 7000 or above. I receive the following error code in response from the api. 'Connection aborted.', RemoteDisconnected('Remote end closed connection without response',) msg_dict['test'] = test msg_dict_json = json.dumps(msg_dict) data = { 'apikey': apikey, 'data': msg_dict_json, } res = requests.post('https://api.txtlocal.com/bulk_json/', data=data) return res sample data obj: data={ "api_key": api_key, "data": '{"sender": "abc", "messages": [{"number": "+0000000000", "text": "some text"}], "test": true}' } data['data'] can be over 7000 objects (which is causing the issue) I know there's a limit of 10000 users per api call for this api: https://api.txtlocal.com/bulk_json/ so my payload count always stays less than 10000. PS: The request doesnt rollback, sms are sent to the user even when I get a response as mentioned above. Just I dont receive a positive response and it throws exception. Also i want to mention that I have successfully been able to send 7 to 8000 sms with successful response but now its sending this issue. Any help would be appreciated, thanks. -
(Linux-Ubunto Permission problem) Nginx can't load static/media files from Django Site
this is more of linux permission problem. Im trying to create a website with nginx and django, but I'm getting error 403 forbidden, so my nginx is not able to read my statics files, I'm not experienced with linux(Ubunto) failed to load resource: the server responded with a status of 403 (Forbidden) I will show you my file permissions: ls -ld /home/jamelaumn/myproject drwxr-xr-x 11 www-data www-data 4096 Jul 9 23:25 /home/jamelaumn/myproject ls -ld /home/jamelaumn/myproject/deploystatic drwxr-xr-x 6 www-data www-data 4096 Jul 9 23:22 /home/jamelaumn/myproject/deploystatic ls -ld /home/jamelaumn/myproject/media drwxr-xr-x 4 www-data www-data 4096 Jul 9 23:25 /home/jamelaumn/myproject/media ls -ld /home/jamelaumn/myproject/media/product_images drwxr-xr-x 4 www-data www-data 4096 Jul 9 23:25 /home/jamelaumn/myproject/media/product_images ps aux | grep nginx root 281102 0.0 0.5 195928 6280 ? Ss 14:52 0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on; www-data 281103 0.0 1.2 196552 13340 ? S 14:52 0:00 nginx: worker process root 281116 0.0 0.1 3452 1576 pts/0 S+ 15:00 0:00 grep --color=auto nginx ps aux | grep /home/jamelaumn/myproject root 281104 0.0 2.3 31048 24280 pts/1 S+ 14:52 0:00 /home/jamelau mn/myproject/venv/bin/python venv/bin/gunicorn django_project.wsgi --bind 127.0. 0.1:8000 root 281105 0.0 4.1 52324 43716 pts/1 S+ 14:52 0:00 /home/jamelau mn/myproject/venv/bin/python venv/bin/gunicorn django_project.wsgi --bind 127.0. 0.1:8000 root 281193 0.0 0.1 … -
How to access drf(django rest framework) api in local network from different machine?
I deployed a drf api in apache server , when i access it from the same machine it work fine (get and post requests and also database connections all works good) , but when I try it from another machine in the same network i got two errors specially if it's a post request or there is a connection with database , the first one before sending anything it said "HTTP 405 Method Not Allowed" and if I try to send post requests it said "CSRF Failed: CSRF token missing or incorrect." and also if there is a get request has connections to database i got 500 server error . I tried to follow the documentation and also looked for these questions 1 , 2 but didn't help , actually I'm not even sure what cause these problems . Note : when i try just runserver command it works fine from other machines . here is virtual host and settings.py . virtual host: <VirtualHost 192.168.100.102:8001 _default_:8001> DocumentRoot /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject ServerAdmin yaz@gmail.com # Set the path to your Django project WSGIDaemonProcess myproject python-home=/opt/bitnami/projects/chatbotQZ/sources/env/ python-path=/opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject WSGIProcessGroup myproject WSGIScriptAlias / /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject/wsgi.py # Configure access to static files Alias /static/ /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/static <Directory /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/static> Require all … -
While Clicking On Razorpay Pay Now Using CARD / WALLET The New Tab Is about:blank#blocked , Django
I used to integrate django and razor pay , but when i click on pay now on options like , card , wallet , ( the payment needed to be in open in new tab ) the page become blank , i cannot access the success page Note: Upi is working and i am getting the result in dashboard , also payment id is generated and its reflecting in razorpay dash board Script Also Loaded My template .html <button id="rzp-button1" class="btn btn-primary my-2 w-100">Pay with Razorpay</button> <script> var options = { "key": "KEY", // Enter the Key ID generated from the Dashboard "amount": "{{payment.amount}}", // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise "currency": "INR", "name": "Acme Corp", "description": "Test Transaction", "image": "https://example.com/your_logo", "order_id": "{{payment.id}}", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1 // "callback_url": "https://eneqd3r9zrjok.x.pipedream.net/", "prefill": { "name": "Gaurav Kumar", "email": "gaurav.kumar@example.com", "contact": "9000090000" }, "handler": function (response){ alert(response.razorpay_payment_id); alert(response.razorpay_order_id); alert(response.razorpay_signature) }, "notes": { "address": "Razorpay Corporate Office" }, "theme": { "color": "#3399cc" }, }; var rzp1 = new Razorpay(options); rzp1.on('payment.failed', function (response){ alert(response.error.code); alert(response.error.description); alert(response.error.source); alert(response.error.step); alert(response.error.reason); alert(response.error.metadata.order_id); alert(response.error.metadata.payment_id); }); document.getElementById('rzp-button1').onclick = function(e){ … -
How to check if model has something inside in django?
I have a model of Branch, and a model of Worker. I want to filter only these branches, which have at least one user inside. models.py class Branch(models.Model): name = models.CharField(max_length=100) class Worker(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=150) branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True, related_name='branch') position = models.CharField(max_length=200) manager = models.BooleanField(default=False) I tried to add related_name to worker-branch, but now I don't know how to use it, and is it right way to do so? I also tried to filter like that: Worker.objects.filter(branch=?).exists(). But it doesn't make sense. At the end I want to have a list of branches which have at least one worker. -
Django. How to write the time to the database in UTC when using the settings 'TIME_ZONE' and 'USE_TZ = True'
There is a Django version 4.0 project. In it, in one of the tables, I use a field to save the datetime. I need the datetime stored in UTC in the database PostgreSQL. What I did: settings.py ... USE_TZ = True TIME_ZONE = "UTC+3" ... models.py class ManualMeasurements(models.Model): ... timestamp = models.DateTimeField(auto_now=False, auto_now_add=False, default=timezone.now) .... At the same time, migration to PostgreSQL created field with time zone: "timestamp" timestamptz NOT NULL Ok, but according to the documentation, this is enough so that in the form of the admin panel, the time in this field is displayed in the time field specified in settings.py , and the database was written in UTC. But no. I found that the database is currently written like this: 2023-07-10 14:55:17.000 +0300 In admin.py I'm overriding the save method: def save_model(self, request, obj: ManualMeasurements, form, change, debug=True): if obj.timestamp: obj.timestamp = obj.timestamp.astimezone(time_func.get_timezone('UTC')) super().save_model(request, obj, form, change) And still in the database I get the time in the current time zone with the time zone indication. What am I doing wrong and how do I get what I need? -
How to change the default language and add it_IT.UTF-8 locale to locale.gen on Azure?
I'm trying to change the default language on the Azure machine hosting my app. Currently, the default language is set to en_US.UTF-8 and is the only one in locale.gen, but I need to configure it to it_IT.UTF-8 to support my Django project. When I start my app and the Django app execute the "import locale" command followed by "locale.setlocale(locale.LC_TIME, 'it_IT.utf8')", I get the "unsupported locale setting" error. I suspect that the Italian language is not properly configured in the system. What are the necessary steps to change the default language and add the it_IT.UTF-8 locale to locale.gen on Azure? Or any others solution? Thank you in advance for your assistance! I created a startup.sh file in the home directory (the only persistent location) with the following commands: echo "it_IT.UTF-8" >> locale.gen locale-gen Then, in the Azure App configuration under General settings, I specified the path /home/startup.sh in Stack Settings > Startup Command. However, when I attempted to start the machine with this configuration, the startup failed for unknown reasons. I expected the startup.sh script to modify the locale.gen file and generate the it_IT.UTF-8 locale successfully. -
проблема в django. Проблема с кодировкой в uri [closed]
после деплоя Django проекта на хостинг. Слетает кодировка в киррилических url enter image description here во время get запроса не находит запись enter image description here На локальной машине все было нормально. На хостинге такая беда Не находит данные в бд. Из-за кода на киррилице -
Unexpected behavior of class method arguments [duplicate]
While writing the next unit test, I discovered the non-obvious behavior of the argument in the class method. The create_data method was supposed to create a dictionary with the default values of the arguments on each call. However, it turned out that if, after creating the dictionary, you change the value of one of the keys, then now IT will become default. from rest_framework.test import APITestCase class Test(APITestCase): def create_data(self, foo={'foo': 1}): return {'foo': foo} def test_1(self): default_data = self.create_data() print(default_data) # {'foo': {'foo': 1}} default_data['foo']['foo'] = 2 print(default_data) # {'foo': {'foo': 2}} def test_2(self): default_data = self.create_data() print(default_data) # {'foo': {'foo': 2}} Thus, after changing the value in the dictionary in the test_1 method, in the test_2 method, create_data will return a dictionary with the value that we set in test_1. Linter flake8 writes: Do not use mutable data structures for argument defaults. They are created during function definition time. All calls to the function reuse this one instance of that data structure, persisting changes between them. However, doesn't the line "All calls to the function reuse this one instance of that data structure" mean that each method call should use the original data structure written when the method … -
Sending email after Login Django Allauth
I’m new using Django Allauth, is there a way I can implement sending email after login? For example; every time someone logged into my account I will receive an email automatically. -
Django - Default schema (dbo) to custom schema name for native django apps?
I would like django to change the reference to the native django table(s) schema(dbo) as seen in the sql below. I have renamed the schema to meta in SQL, but when I run the app, it recreates the tables on the dbo schema again in the DB. So I deleted them again and renamed my meta schemas back to dbo in TSQL and tried to get django to migrate them to the new schema name by running, python manage.py inspectdb > models.py The models.py generates and then changing the following in the models.py file in the root folder. eg. class AuthGroup(models.Model): # model fields... class Meta: db_table = 'meta.auth_group' Then I run makemigrations and then migrate does not detect the models.py changes. Is this the correct approach or are we still stuck in changing the user running django to have a default schema to be set to "meta"? ALTER SCHEMA dbo TRANSFER [meta].[django_admin_log] ALTER SCHEMA dbo TRANSFER [meta].[admin_interface_theme] ALTER SCHEMA dbo TRANSFER [meta].[auth_group] ALTER SCHEMA dbo TRANSFER [meta].[auth_group_permissions] ALTER SCHEMA dbo TRANSFER [meta].[auth_user] ALTER SCHEMA dbo TRANSFER [meta].[auth_user_groups] ALTER SCHEMA dbo TRANSFER [meta].[auth_user_user_permissions] ALTER SCHEMA dbo TRANSFER [meta].[django_content_type] ALTER SCHEMA dbo TRANSFER [meta].[django_migrations] ALTER SCHEMA dbo TRANSFER [meta].[django_session] ALTER SCHEMA … -
Django how to display a pdf in canvas-wrapper
I have been given a task to make a page.inside it should be a Pdf that people can read without downloading if they don't want to. Now the problem is that meanwhile i can embed or Iframe the pdf i can not display it in way the template has been given to me Loading... <div class="spinner-grow text-primary" role="status"> <span class="visually-hidden">Loading...</span> </div> <div class="spinner-grow text-primary" role="status"> <span class="visually-hidden">Loading...</span> </div> </div> <canvas id="pdf-canvas" class="onload-pdf" data-url="{% static 'apply/pdf/terms.pdf' %}"> </canvas> </div> As you can see there is a canvas wrapper that pdf should be inside how can i do that? -
How to make crud operation on Django without page reload
Hello I am trying make crud operation on Django without page reload and also implement Django Form validation like duplicate messages and error messages -
how to host projects in pythonAnywhere, when i'm try to do i have got an error
when I'm going to do app deployment , open my pythonAnywhere--->console---->bash I've to make virtual environment first, but I got an error here my command is:- 09:19 ~ $ mkvirtualenv test --python=usr/bin/python3.11 got Error is below :- RuntimeError: failed to find interpreter for Builtin discover of python_spec='usr/bin/python3.11 I tried to do but actually got this error:- error in Bash console -
Django unique_together with df.to_sql not working
I am using df.to_sql to insert data into database table. But I don't want to have some duplicated rows for some columns. I tried unique_together but it doesn't seem working. class InsertionOrdersRealSpents(InsertionOrdersCommonFields): def __str__(self): return "%s" % self.insertion_order # return "{}".format(self.insertion_order) class Meta: db_table = 'InserstionOrdersRealSpents' unique_together = ['date', 'advertiser', 'dsp', 'insertion_order', 'impressions'] Any method or suggestion? If there is identical row in the database, skip that row in the file to upload ? -
Could not parse the remainder: '|' from '|' in Django template while paginating
while paginating the blog app , the following error showed up. TemplateSyntaxError at /home/ Could not parse the remainder: '|' from '|' Request Method: GET Request URL: http://127.0.0.1:8000/home/?page1 Django Version: 4.2.2 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '|' from '|' Exception Location: C:\Users\chand\venv\Lib\site-packages\django\template\base.py, line 703, in init Raised during: blog.views.PostListView Python Executable: C:\Users\chand\venv\Scripts\python.exe Python Version: 3.11.3 Python Path: ['C:\Users\chand\django_project', 'C:\Users\chand\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\chand\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\chand\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\chand\AppData\Local\Programs\Python\Python311', 'C:\Users\chand\venv', 'C:\Users\chand\venv\Lib\site-packages'] Server time: Mon, 10 Jul 2023 10:24:46 +0000 This was the html template I wrote: {% extends "blog/base.html" %} {% block content %} {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post_detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="{{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info mb-4" href="?page={{ num }}">{{num}}</a> {% elif num > page_obj.number | add:'-3' and num < page.obj.number | add:'3' %} <a class="btn btn-outline-info … -
Angular HTTP DELETE request not working with Django backend
I am facing an issue with performing HTTP DELETE requests from my Angular frontend to my Django backend. The deletion works fine when testing it with Django Postman, but it fails to work when triggered from the Angular interface. Here is the relevant code snippet: deleteClick(item: any) { if (confirm('Are you sure?')) { const departmentToDelete = { DepartmentId: 145742, DepartmentName: 'TELECOMM', description: 'it is a department to sale' }; this.service.deleteDepartment(departmentToDelete).subscribe( (data) => { alert(data.toString()); this.refreshDepList(); }, (error) => { console.log('Error occurred while deleting the department:', error); alert('Error occurred while deleting the department.'); } ); } } Backend code (Django): elif request.method == 'DELETE': department_data = JSONParser().parse(request) department = Departments.objects.get(DepartmentId=department_data['DepartmentId']) department.delete() return JsonResponse("Deleted Successfully!!", safe=False) When triggering the deletion from the Angular interface, I receive the following error in the console rest_framework.exceptions.ParseError: JSON parse error - Expecting value: line 1 column 1 (char 0) [10/Jul/2023 12:00:02] "DELETE /department/145742 HTTP/1.1" 500 98390 I have verified that the URL and headers are correct, and the request payload seems to be in the expected JSON format. However, I can't figure out why the deletion is not working in the Angular interface. Any help or guidance on how to troubleshoot and resolve this issue would … -
update_or_create only for first record
I want to check if multiple records are equal to IS_USABLE = False then update only one record to IS_USABLSE = True.But it fails. new_invoice = N_INVOICE.objects.update_or_create(INVOICE_IS_USABLSE = False, defaults={'INVOICE_IS_USABLSE':True,})[0] -
System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'admin' isn't unique
System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace No installed app with label 'first_app'. In terminal after I typed python manage.py make migrations first_app I am facing this issue. Plz help -
How can we run two services with one common model DB in Django?
How can we run two services with one common model DB in Django? I have project structures like below A Project has Model C in its project. ( which should be public ) B Project has Model C in its project. ( which should not be public ) They share Model C. But when Project B needs to change Model C then we had to manually change model script of Project A. It created many problems. How can we deal with this? Should we merge two projects in two apps on one project? Then How can we make only one app private? -
ModuleNotFoundError: No module named 'bootstrap5' getting this error after moving my django project to docker
Hi I just moved my Django project on the docker. And created an image successfully. But when,I tried running it using docker run -p 8000:8000 my-django-app I am getting the error Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.11/threading.py", line 1038, in _bootstrap_inner self.run() File "/usr/local/lib/python3.11/threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'bootstrap5' I have even added the bootstrap5 in the django settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'firstapp', 'bootstrap5', ] And I have added it in the requriments.txt django-bootstrap5==23.3 This if my dockerfile # Use an official Python … -
Kafka and Django management command
Hello everyone hope I find you well! So I'm trying to setup a new project with Django and a Kafka consumer. I'm using confluent-python package to create my consumer. So I'm facing a very odd situation. When I start my project through my docker entrypoint I run a django management command with the following code: import simplejson from confluent_kafka import Consumer from django.core.management import BaseCommand from loguru import logger from apps.<my_service> import KafkaHandler class Command(BaseCommand): help = "Start Reporting Kafka Consumer" def handle(self, *args, **kwargs): logger.debug("Starting consumer") consumer = Consumer( {"bootstrap.servers": "kafka:19091", "group.id": "reporting"} ) consumer.subscribe(["test_producer"]) kafka_handler = KafkaHandler() try: while True: logger.debug("Consuming") msg = consumer.poll(1.0) if msg is None: continue if msg.error(): logger.debug(f"Consumer error: {msg.error()}") continue event_message = msg.value().decode() logger.debug(f"Received message: {event_message}") json_message = simplejson.loads(event_message) kafka_handler.handle(json_message) finally: consumer.close() After I start my project through command docker-compose up I see that the log "Start consumer" is printed two times and that I have two consumer connections instead of only one so I suspect that this code is being run twice which is very odd. Can someone help me with this situation? Bellow I share my docker-entrypoint !/bin/bash set -e if [[ "${PROJECT_RUN_MODE}" == "production" ]]; then exec <run production mode> … -
Django + SQLite3 in Docker - Database automatically rolled back to initial state after new Docker build and start
I have a Django project which uses SQLite3 database running in Docker container. Dockerfile: # Base image FROM python:3.10-slim-buster # Set working directory WORKDIR /app # Copy the entire project directory COPY . /app # Install project dependencies RUN pip install -r requirements_dev.txt # Expose port EXPOSE 8000 # Run the development server CMD ["python", "doc_manager/manage.py", "runserver", "0.0.0.0:8000"] docker-compose.yml: version: '3' services: web: build: context: . dockerfile: Dockerfile ports: - "8000:8000" volumes: - ./:/app/doc-manager-web When I want to build/deploy new version in this set-up, I execute these 2 commands: docker compose build docker compose up Both commands are successfully executed. But, consider this use case: I deploy the current version using the given set-up. I perform some modifications in the database (CRUD operations). The database is now modified. I then perform some changes in the code itself (not in the Dockerfile or in docker-compose.yml). I re-run the docker compose build and docker compose up commands. Then, I end up with the initial state of the database without the modifications I performed in step number 2. How do I make sure that my SQLite3 database keeps it's modifications regardless of the code modifications I'll do in the future and regardless of … -
Why did I get 302 Error instead of the asked page in Django
When I try to go to the update page for my "Project" object by pressing a button, Page load, and nothing happend (just return the same page). url behind is "/projects/1/update". I have the same behavior for and other object called "Version". (Pression but and go to update page). But for this one it's works properly. the part url.py the part views.py I checked following issues: URL is correctly generated by "{% url ... %}" in the template I'm testing it with a admin account, permission shall be correct. The view.py, and URL, are the same as for Version, (where it's works). template "projects/project_form.html" also exist. When put the URL "http://localhost:8000/projects/1/update" in the URL I get the code 302 and go back to home "/". Someone has an Idea why could be go wrong ?