Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to retrieve object ids present in a form at POST request processing time
I have a Django form that contains a table with rows that reflect course objects from a database . Each row contains a checkbox input . When the form is submitted , I want to update which courses are checked and unchecked into the user profile. To do that I need to know which inputs are checked , which I know how to retrieve, but I also need to know which inputs are unchecked . This is not as easy as ‘all the others’ because my table does not always contain all course objects from the database. Its often a filtered set. So I need to know which courses are present in the table. Of course I know this at rendertime, but I dont know how to retrieve it at POST request processing time. I have been researching but am unsure about the best way to solve this problem. I read something about using hidden inputs , which I could give a try. The idea would be to give each row a hidden input with the course id, which I could retrieve when the form is submitted. I am curious if this would be the way to go. Or if … -
WebSocket disconnected with code: 1011 in django
consumers.py import asyncio import websockets import sounddevice as sd import vosk import queue from channels.generic.websocket import AsyncWebsocketConsumer model_path = "vosk_model/vosk-model-small-en-us-0.15" model = vosk.Model(model_path) sample_rate = 16000 audio_queue = queue.Queue() class SpeechRecognitionConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() self.rec = vosk.KaldiRecognizer(model, sample_rate) print("WebSocket connection accepted") async def receive(self, bytes_data): audio_queue.put(bytes_data) await self.process_audio() async def process_audio(self): while not audio_queue.empty(): data = audio_queue.get() if self.rec.AcceptWaveform(data): result = self.rec.Result() result_dict = json.loads(result) recognized_text = result_dict.get('text', '') print("recognized_text: ", recognized_text) print("Final Result: ", recognized_text) await self.send(text_data=json.dumps({ 'type': 'result', 'text': recognized_text })) else: partial_result = self.rec.PartialResult() partial_dict = json.loads(partial_result) partial_text = partial_dict.get('partial', '') print("Partial Result: ", partial_text) await self.send(text_data=json.dumps({ 'type': 'partial', 'text': partial_text })) async def disconnect(self, close_code): print(f"WebSocket disconnected with code: {close_code}") audio.py import asyncio import websockets import sounddevice as sd async def send_audio_data(websocket): loop = asyncio.get_event_loop() def audio_callback(indata, frames, time, status): if status: print(f"Audio Status: {status}") audio_data = bytes(indata) print(f"Received audio data of length: {len(audio_data)}") asyncio.run_coroutine_threadsafe(websocket.send(audio_data), loop) with sd.RawInputStream(samplerate=16000, channels=1, dtype='int16', blocksize=1024, callback=audio_callback): print("Recording and sending audio data...") while True: await asyncio.sleep(0.05) async def main(): uri = "ws://localhost:8000/ws/recognize/" async with websockets.connect(uri) as websocket: print("Connected to WebSocket server") await send_audio_data(websocket) # Create an event loop loop = asyncio.get_event_loop() loop.run_until_complete(main()) I'm developing a speech recognition feature in … -
JQuery editable select after Ajax call in Django
I'm using JQuery editable select in a Django project to make select widgets searchable. When I'm calling another template containing selectboxes with Ajax, the script won't apply unless I use : $.getScript("https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js").then(() => {} The problem is that it makes the rendering of the Ajax very slow and random. Is there a way to cache the script in the parent template and load it only once so I can reuse it when I'm rendering the child template ? Here is my AJAX call on parent template : $.ajaxSetup( { data: {select_update_record_project_id: sales_documents_id , csrfmiddlewaretoken: '{{ csrf_token }}' }, }); $.ajax({ type: "GET", url: "/my_url/", cache: true, // I have tried both true and false beforeSend: function(){ $('#div_master_sales_documents_edit').empty() }, success: function (data) { $.getScript("https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js").then(() => { $("#div_master_sales_documents_edit").html(data); }); } }); } Here is my child template rendered after Ajax call : <select id="sales_documents_editable_select_description_1"></select> <select id="sales_documents_editable_select_description_2"></select> <select id="sales_documents_editable_select_description_3"></select> <script> // this is where you apply the editable-select to select widgets var list_selectbox_ids = ['sales_documents_editable_select_description_1','sales_documents_editable_select_description_2','sales_documents_editable_select_description_3']; for (let i = 0; i < list_selectbox_ids.length; i++) { $('#' + list_selectbox_ids[i]).editableSelect({effects: 'fade'}).on('select.editable-select', function (e, li) { populate_sales_documents_selected_product($('#' + list_selectbox_ids[i]).attr('id'), li.text(), li.val()) }); } </script> -
How to handle multiple products in a sale with instalment payments in Django/MySql?
I'm building an inventory management system using Django where clients can purchase multiple products in different quantities as part of a single sale. The client may also pay for the sale in installments, rather than paying for each product individually. Current Tables/Models: Client: Records first name last name and the type of the client (e.g enterprise or regular person). Product: Records name and stock unit that describes the quantity of this product and a description of the item. Sell: Records sales. Buy: Records product buyings (e.g restocking) Payment: Records client payments. The issue: I need a way to: Allow the client to make payments in installments for the total sale price. Update the status of the sale ("pending" or "completed") based on whether the client has fully paid for the sale. Track the whole sale instead of relying on each product. Current models: class Product(models.Model): name = models.CharField(max_length=150) description = models.TextField() stock_unit = models.PositiveIntegerField() created_at = models.DateTimeField(default=timezone.now) numero_bl = models.CharField(max_length=30,null=True, blank=True) def __str__(self): return self.name # ----------------------------------------------------------- class Client(models.Model): CLIENT_TYPE_CHOICES = [ ('particulier','Particulier'), ('entreprise','Entreprise'), ] first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) client_type = models.CharField( max_length=20, choices=CLIENT_TYPE_CHOICES, default='particulier' ) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return f"{self.first_name} {self.last_name} ({self.client_type})" # ----------------------------------------------------------- class … -
django admin Unknown error for user registration
When I added USER to admin and then registered and created a new class for his admin, Django showed me this error. from django.contrib import admin from .models import * class CategoryAdmin(admin.ModelAdmin): list_display = ("name",) class JobAdmin(admin.ModelAdmin): list_display = ("id", "title", "description", "salary", "created_at", "updated_at", "category") class UserAdmin(admin.ModelAdmin): list_display = ("id", "name", "lastname", "country", "age") admin.site.register(Category, CategoryAdmin) admin.site.register(Job, JobAdmin) admin.site.register(JobUser, UserAdmin) I wanted to add a new column User in my admin to see and manage him. -
how can i make many to many relationship between my two models successfully in my project in django?
after i made aproject by flask and sqlite iwant to make it by django i succeeded in adding foods to certain date and calculates the total calories but i fail to show the days with total calories in the home page i show only the days that i added to my model but can not show its detail from total protein and fats and calories so i want asoluation in create_date function in my view and here is my project details first my model from django.db import models from datetime import datetime # Create your models here. class Food(models.Model): name=models.CharField(max_length=512,unique=True) protein=models.IntegerField(null=False) carbohydrates=models.IntegerField(null=False) fats=models.IntegerField(null=False) calories=models.IntegerField(null=True) def total_calories_food(self): total=self.protein * 4 + self.carbohydrates * 4 + self.fats * 9 self.calories=total self.save() def __str__(self): return f'{self.name}' class Dates(models.Model): food=models.ManyToManyField(Food,through='DatesFoods') date=models.DateField() class DatesFoods(models.Model): date_id=models.ForeignKey(Dates,on_delete=models.CASCADE) food_id=models.ForeignKey(Food,on_delete=models.CASCADE) second my forms: from django import forms from .models import Food, Dates class Food_Form(forms.ModelForm): class Meta(): model = Food fields = ('name', 'protein', 'carbohydrates', 'fats') class Dates_Form(forms.ModelForm): class Meta(): model = Dates fields = ('date',) and finally my views def create_date(request): form=Dates_Form(request.POST) dates = Dates.objects.all() if form.is_valid(): form.save() return render(request,'foodlist/home.html',context={'form':form,'dates':dates, }) def add_food(request): form=Food_Form(request.POST) if form.is_valid(): form.save() foods=Food.objects.all() for d in foods: d.total_calories_food() return render(request,'foodlist/add_food.html',context={'form':form,'foods':foods}) def view_foods_day(request,date): d=get_object_or_404(Dates,date=date) print(d) … -
Query Model with Many to Many Field with empty list as input
I have a model that contains a many to many field: class Transaction(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False, primary_key=True) transaction_date = models.DateField(null=False, blank=False) transaction_category = models.ForeignKey(Category, on_delete=models.PROTECT, null=False, blank=False) customer_vendor = models.ForeignKey(CustomerVendor, on_delete=models.PROTECT, blank=False, null=False) account = models.ForeignKey(Account, on_delete=models.PROTECT, blank=False, null=False) reimbursable = models.BooleanField() tag = models.ManyToManyField(Tag, blank=True) amount = models.DecimalField(max_digits=12, decimal_places=2, null=False, blank=False) description = models.CharField(max_length=255, null=False, blank=False) I have a query that gets me transactions: Transaction.objects.filter(transaction_category__master_category__category_type="Income", transaction_date__range=[start_date, end_date]).filter(exclude_reimbursable).order_by().annotate(month=ExtractMonth("transaction_date"), year=ExtractYear("transaction_date")).values("month", "year").annotate(month_year=Concat("month", V(" "), "year", output_field=CharField()), month_total=Sum("amount")).values("month_year", "month_total").order_by("year", "month") I am trying to add the Tag (many to many field) to the query. From the web app, I get all the tags that a user selected as a list. The list could also be empty and have 0 tags. I tried using tag__in=tags in the query, but if a user does not select any tags, it does not work. If a user does not select any tags, we should treat it like any transaction can be returned even if it does not have any tags selected. I have also tried using Q(tag__in=tags) | Q(tag=None) to get transactions that have any tag OR no tag, which should do what I want, but it always returns an empty query set. -
Cannot access Google Cloud Storage bucket from GitHub Actions Workflow
I have the Django test case test_retrieve_bucket to test access to a GCP storage bucket. from django.test import SimpleTestCase, TestCase from google.cloud import storage class DemoTest(TestCase): def setUp(self): self.expense = Expense.objects.create( invoice_number = "ABC", account_number = "123", customer_name = "XYZ", invoice_amount = 12.50, invoice_date = datetime.now() ) def test1(self): return self.expense.invoice_number == "ABC" def test2(self): return self.expense.account_number == "123" def test3(self): return self.expense.customer_name == "XYZ" def test_retrieve_bucket(self): bucket = "test_bucket_8866" client = storage.Client() bucket = client.bucket(bucket) return self.assertTrue(bucket.exists()) However, the test fails, and this is the error I am receiving: google.api_core.exceptions.Forbidden: 403 GET https://storage.googleapis.com/storage/v1/b/test_bucket_8866?fields=name&prettyPrint=false: test-service-account@tbi-finance.iam.gserviceaccount.com does not have storage.buckets.get access to the Google Cloud Storage bucket. Permission 'storage.buckets.get' denied on resource (or it may not exist). I successful authenticated the service account with Workload Identity Federation in the previous step: The service account I used also has Storage Object Admin permission, which should give me access to the bucket: Here is my workflow file: name: Django CI on: push: branches: [ "main" ] pull_request: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.12.4] steps: - uses: actions/checkout@v4 - name: auth uses: google-github-actions/auth@v2.0.0 with: workload_identity_provider: 'projects/334572487877/locations/global/workloadIdentityPools/learn-github-actions-pool/providers/github-cdci' service_account: 'test-service-account@tbi-finance.iam.gserviceaccount.com' - name: Set up Python ${{ matrix.python-version }} … -
JQuery - use static file in getscript
In one of my script, I'm using $.getScript("https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js").then(() => {...}); to get a script before going on. Loading this script via https is very time consuming so I saved this file to my static folder in django as jquery-editable-select.min.js how can I use my static js file instead of the https:// url inside $.getScript ? I tried $.getScript("{% static 'my/path/from/static/folder/jquery-editable-select.min.js'%}").then(() => {...}); but it's not working -
The request failed to reach my Django view
This is a web Django project, In my navbar I have a drop down that contains buttons to exploring products depending on their category, here is the code of the drop down list snippet in the main template: <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Product Categories </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <button data-category = "cloths" class="product-category dropdown-item btn btn-light">Cloths</button> <button data-category = "sport" class="product-category dropdown-item btn btn-light">Sport</button> <button data-category = "household items" class="product-category dropdown-item btn btn-light">Household items</button> </div> </li> and I used csrf token for post requests, and here is the javascript snippet: var productCategories = document.getElementsByClassName("product-category") for ( i = 0 ; i < productCategories.length ; i ++ ) { productCategories[i].addEventListener('click', function(){ var category = this.dataset.category console.log(category) exploringCategory(category) }) } function exploringCategory(category) { var url = 'category_exploring/' fetch(url,{ method:'POST', headers:{ 'Content-Type' : 'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'category' : category}) }) } and here is the view: def category_exploring(request): data = json.loads(request.body) category = data['category'] print('*') print(category) user = request.user products = Product.objects.filter(category=category) order, created = Order.objects.get_or_create(customer = user, complete = False) cartItems = order.get_total_order_cnt context = {'products' : products, 'cartItems': cartItems} return render(request, 'store/store.html', context) the problem is nothing is happening when I click … -
Django performance issue on render after upgrade to Django 4.2
I'm upgrading an old Django project to Django 4.2. Everything seems to be working, except that performance on pages has degraded by factor of 100x. I profiled the views and everything is still performing correctly. The issue seems to be around rendering the template or perhaps the middleware. I used the Django debug toolbar and I'm seeing that all the time is spent on an exception when processing the request. Any idea on what might be happening, or how I can get more information about this exception? Call CumTime Per TotTime Per Count - /debug_toolbar/panels/__init__.py in process_request(196) 37.600 37.600 0.000 0.000 2 /django/core/handlers/exception.py in inner(52) 37.600 37.600 0.000 0.000 1 -
TypeError: '<' not supported between instances of 'CombinedExpression' and 'int' when trying to implement the post_save signal with django-axes
I'm trying to create a signal which sents an email informing about an access attempt, when a user fails to provide correct credentials when logging in. Access attempts are traced by the django-axes package. If the failure_limit is reached, an another signal is used. Comparing both values determines if this signal is used at the moment. The TypeError occurs in failures = instance.failures_since_start. from axes.models import AccessAttempt from django.db.models.signals import post_save from django.dispatch import receiver from django.core.mail import mail_admins from django.template import loader from tajnanorka.settings import AXES_FAILURE_LIMIT @receiver(post_save, sender=AccessAttempt) def login_attempt_email(sender, instance, **kwargs): def _render_email_message(context): template = loader.get_template("foo.html") return template.render(context) failures = instance.failures_since_start failure_limit = int(AXES_FAILURE_LIMIT) context = dict( failures_since_start = failures, ) subject = 'bar' message = _render_email_message(context) if failures < failure_limit: mail_admins( subject, message, fail_silently=False, html_message = message ) AccessAttempt model: class AccessBase(models.Model): user_agent = models.CharField(_("User Agent"), max_length=255, db_index=True) ip_address = models.GenericIPAddressField(_("IP Address"), null=True, db_index=True) username = models.CharField(_("Username"), max_length=255, null=True, db_index=True) http_accept = models.CharField(_("HTTP Accept"), max_length=1025) path_info = models.CharField(_("Path"), max_length=255) attempt_time = models.DateTimeField(_("Attempt Time"), auto_now_add=True) class Meta: app_label = "axes" abstract = True ordering = ["-attempt_time"] class AccessAttempt(AccessBase): get_data = models.TextField(_("GET Data")) post_data = models.TextField(_("POST Data")) failures_since_start = models.PositiveIntegerField(_("Failed Logins")) def __str__(self): return f"Attempted Access: {self.attempt_time}" class Meta: … -
Generating an arabic pdf file using Django and xhtml2pdf
I want to generate an arabic pdf file using django and xhtml2pdf library. My code is this In the views.py class ViewPDF(View): def get(self, request, *args, **kwargs): name=أفراد.objects.get(رقم_شخصي="100056").الإسم data={"name":name} pdf = render_to_pdf('pdf_template.html', data) return HttpResponse(pdf, content_type='application/pdf') def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return pdf first i followed xhtml2pdf api to generate a pdf file. first i created a render_to_pdf method to create the needed pdf file. second, i inserted the desired data into the template. The template i'm using : {% load static%} <html dir="rtl"> <pdf:language name="arabic"/> <head> <title>ملف الشخصي</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Noto+Naskh+Arabic:400,700" rel="stylesheet"> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <style> @page { size: a4 portrait; @frame header_frame { /* Static Frame */ -pdf-frame-content: header_content; left: 50pt; width: 512pt; top: 50pt; height: 40pt; } @frame content_frame { /* Content Frame */ left: 50pt; width: 512pt; top: 90pt; height: 632pt; } @frame footer_frame { /* Another static Frame */ -pdf-frame-content: footer_content; left: 50pt; width: 512pt; top: 772pt; height: 20pt; } body { direction:rtl; } } </style> </head> <body> <!-- Content for Static Frame 'header_frame' --> <div id="header_content"> <h3>ملف الشخصي</h3> </div> For arabic it's not working <!-- Content for … -
How to change Root User to Custom User in Dockerfile
I've been attempting to make all users in my Dockerfile to custom user as when running collectstatic in my Django app I get a error message [Errno 13] Permission denied: '/code/static/admin/js/vendor/select2/i18n/pl.6031b4f16452.js.gz'. I also want to do so for security reasons. Currently when I run >docker-compose exec web ls -l /code/static I get total 16 drwxrwxrwx 1 root root 4096 Apr 5 05:42 admin drwxrwxrwx 1 root root 4096 Sep 18 21:21 css drwxrwxrwx 1 root root 4096 Sep 18 21:21 human drwxrwxrwx 1 root root 4096 Sep 18 18:42 img -rw-r--r-- 1 1234 1234 13091 Sep 18 21:21 staticfiles.json drwxrwxrwx 1 root root 4096 Sep 18 21:21 transcribe Here is my Dockerfile: # Pull base image FROM python:3.11.4-slim-bullseye # Set environment variables ENV PIP_NO_CACHE_DIR off ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV COLUMNS 80 #install Debian and other dependencies that are required to run python apps(eg. git, python-magic). RUN apt-get update \ && apt-get install -y --force-yes python3-pip ffmpeg git libmagic-dev libpq-dev gcc \ && rm -rf /var/lib/apt/lists/* # Set working directory for Docker image WORKDIR /code/ # Install dependencies COPY requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . # Create a … -
How to be logged in two different project in django
I have two Django applications, app1, and app2, both using the same database and running on different ports (localhost:8000 and localhost:8010). When I log in to app1, I want the user to be automatically logged in to app2 as well. Currently, both apps are using the database session engine, but I haven't configured caching yet. I have a plan to set up Redis for caching and session management to enable session sharing between the two applications. -
How To Validate Messages Containing Profane Words In Django
[forms.py[offensive.py[utils.py[views.pyhtml file](https://i.sstatic.net/H3wrNZfO.jpg)](https://i.sstatic.net/2iAK2sM6.jpg)](https://i.sstatic.net/Jgvafw2C.jpg)](https://i.sstatic.net/2GVLdtM6.jpg) I am asking this question in stackoverflow "I have a django anonymous project where by anonymous users send messages. Messages shouldn't include profane words. I have created an offensive.py file that contains all the words, a utils file and the HTML file and included a function in the form file to handle that. But after submiting any word that is profane(in the offensive.py file ) i get no alert and the message is sent with no error. i have attached the images of the code. i have no error in the code but the profane language detection feature is not working. -
How do I instrument and configure a django app with OTel?
I created a sample django app that accepts to endpoint. My goal is to instrument it with OTel so that it will report the following metrics for each endpoint: Error rate Latency (And hopefully to do so without explicitly set each endpoint with specific code.) I tried OpenTelemetry WSGI Instrumentation but I couldn't find how to configure it to export metrics to the OTel collector. Is the WSGI instrumentation suppose to accompany the OTEL instrumentation? Do I need to instrument my code with both to be able to configure it? In short, my question is how do I configure the OTel instrumentation to export the above metrics to the OTel collector or Prometheus endpoint? -
Javascript fetching code instead of name within Django
This is a javascript that I have found in github, this is the link for it the problem is that when I used the ph-address-selector.js, it works but instead of fetching the "display name", it fetches the "code ids", which is the true value of the input when I ask ChatGPT about it. Also you can see the same issue from some user. so I tried the modified javascript code so that it will use the same url I used to connect it to my base.html, which extends all of my scripts to all of my html templates. ph-address-selector.js var my_handlers = { // fill province fill_provinces: function() { var region_code = $(this).val(); var region_text = $(this).find("option:selected").text(); $('#region-text').val(region_text); $('#province-text').val(''); $('#city-text').val(''); $('#barangay-text').val(''); let dropdown = $('#province'); dropdown.empty().append('<option selected="true" disabled>Choose State/Province</option>'); let city = $('#city'); city.empty().append('<option selected="true" disabled></option>'); let barangay = $('#barangay'); barangay.empty().append('<option selected="true" disabled></option>'); $.getJSON(provinceUrl, function(data) { var result = data.filter(value => value.region_code == region_code); result.sort((a, b) => a.province_name.localeCompare(b.province_name)); $.each(result, function(key, entry) { dropdown.append($('<option></option>').attr('value', entry.province_code).text(entry.province_name)); }); }); }, // fill city fill_cities: function() { var province_code = $(this).val(); var province_text = $(this).find("option:selected").text(); $('#province-text').val(province_text); $('#city-text').val(''); $('#barangay-text').val(''); let dropdown = $('#city'); dropdown.empty().append('<option selected="true" disabled>Choose city/municipality</option>'); let barangay = $('#barangay'); barangay.empty().append('<option selected="true" disabled></option>'); $.getJSON(cityUrl, … -
Celery + RabbitMQ random Connection reset by peer
I'm using celery in django with rabbitmq, it works fine but some times it gives ConnectionResetError traceback: [2024-09-18 07:08:31,427: ERROR/MainProcess] Error cleaning up after event loop: RecoverableConnectionError(None, 'Socket was disconnected', None, '') Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/celery/worker/loops.py", line 97, in asynloop next(loop) File "/usr/local/lib/python3.11/site-packages/kombu/asynchronous/hub.py", line 306, in create_loop item() File "/usr/local/lib/python3.11/site-packages/vine/promises.py", line 161, in __call__ return self.throw() ^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/vine/promises.py", line 158, in __call__ retval = fun(*final_args, **final_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/kombu/transport/base.py", line 230, in _read drain_events(timeout=0) File "/usr/local/lib/python3.11/site-packages/amqp/connection.py", line 526, in drain_events while not self.blocking_read(timeout): ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/amqp/connection.py", line 531, in blocking_read frame = self.transport.read_frame() ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/amqp/transport.py", line 312, in read_frame payload = read(size) ^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/amqp/transport.py", line 629, in _read s = recv(n - len(rbuf)) ^^^^^^^^^^^^^^^^^^^ ConnectionResetError: [Errno 104] Connection reset by peer when checking rabbitmq logs (172.21.0.1:50078 -> 172.21.0.2:5672): user 'test' authenticated and granted access to vhost '/' rabbitmq-1 | 2024-09-19 07:43:51.816951+00:00 [error] <0.43132.0> closing AMQP connection <0.43132.0> (172.21.0.1:50072 -> 172.21.0.2:5672): rabbitmq-1 | 2024-09-19 07:43:51.816951+00:00 [error] <0.43132.0> missed heartbeats from client, timeout: 60s rabbitmq-1 | 2024-09-19 07:45:10.121070+00:00 [notice] <0.86.0> alarm_handler: {set,{system_memory_high_watermark,[]}} rabbitmq-1 | 2024-09-19 07:46:30.182591+00:00 [info] <0.43323.0> accepting AMQP connection <0.43323.0> (172.21.0.1:45394 -> 172.21.0.2:5672) rabbitmq-1 | 2024-09-19 07:46:30.183948+00:00 [info] <0.43323.0> connection <0.43323.0> (172.21.0.1:45394 -> 172.21.0.2:5672): … -
Django: using older version of postgresql
I want to develop a backend with Django and interact with a production database that runs PostgreSQL 12.X. Django 5, however, is only compatible with PostgreSQL 13+. There are the options of writing direct SQL commands hacking Django to overwrite the version check downgrade Django by two major versions, but I'm not happy with either of the solutions. Is there a more elegant way of using PostgreSQL 12 with Django 5? -
Am I using return render(request, url) wrong in django? (CS50)
In Project 1 of Web Development with Python and Javascript with CS50, I made a form class that should create a new wiki page. It's supposed to get the input before using its "action" to trigger a function which will return to the home page from the addpage page once it's done. But using return render() to send the input and other necessary information while redirecting to the home page (something that has worked fine in other functions) doesn't seem to work this time. There's a brief reload and the input just disappears, there's no redirect, and the util.save_entry() hasn't created a new page. Could someone give me a hint where I might've went wrong please? Thanks. The page for adding new pages {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {%block head%} <link rel="stylesheet" href="styles.css"> {%endblock%} {% block body %} <h1>New Page</h1> <div class="formwrapper"> <form action = "{% url 'addpage' %}" method="post"> {% csrf_token %} {{title}} <input type="submit"> </form> </div> {% endblock %} My urls: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<str:page>", views.getpage, name="page"), path("addpage", views.addpage, name="addpage") ] addpage function in views: def addpage(request): if request.method=="POST": title=NewTitle(request.POST) … -
How can I maintain a modified version of a Python library and ensure that my application installs this version automatically using requirements.txt?
I want to avoid manually editing the library code each time I install dependencies and is there a way to get future updates to the library while still preserving my changes? I am currently clueless on how can I achieve this. -
Error "SQLite backend does not support timezone-aware datetimes when USE_TZ is False" when saving DateField in Django
I am working on a Django project using an SQLite database and encountered the following error when trying to save records to the database: SQLite backend does not support timezone-aware datetimes when USE_TZ is False. In my model, I am using two DateField fields as follows: class Announcement(models.Model): date_start= models.DateField(null=True, blank=True) date_end = models.DateField(null=True, blank=True) In my code, I am assigning dates like this: from datetime import datetime, timedelta from coreapp.views.base.base_view import BaseView from coreapp.services import utils from announcement.models import Announcement class FormAnnouncement(BaseView): def post(self, request): form = utils.get_form_from_json(request) date_start = datetime.strptime(form['date_start'], "%Y-%m-%d").date() if 'date_start' in form and form['date_start'] else None date_end = datetime.strptime(form['date_end'], "%Y-%m-%d").date() if 'date_end' in form and form['date_end'] else None new_Announcement = Announcement.objects.get(id=announcement_id) new_Announcement.date_start = date_start + timedelta(days=1) new_Announcement.date_end = date_end + timedelta(days=1) new_Announcement.save() Relevant settings in settings.py: USE_TZ = False Database: SQLite From what I understand, this error usually occurs when working with DateTimeField or datetime, but in my case, I am only using DateField, which should handle just dates without the time component. Does anyone know what could be causing this error and how I can resolve it without changing USE_TZ in the settings.py file? -
AVIF for Django-imagekit?
Let’s say this is my code, powered by django-imagekit. from django.db import models from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFill class Profile(models.Model): avatar = models.ImageField(upload_to='avatars') avatar_thumbnail = ImageSpecField(source='avatar', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) How can this be modified to support AVIF as the target image format? I know JPEG and even WebM is supported. But I don’t think AVIF is. So is there any way this can be modified to accomplish it? -
How to Reuse MongoClient Connections Efficiently in Django with PyMongo?
I'm working on a project using Django version 3.0.8 and PyMongo version 3.11.3. Currently, for each incoming request, a new MongoClient is created, and the connection is destroyed once the request is processed. I think this approach incurs too much overhead due to the constant creation and destruction of connections. Is there a more efficient way to reuse MongoClient connections across requests?