Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django mtpp use multiple add_related_count
i need count items in categories twice with different parametres, how i have to do? obviously that dosen't work bcs add_related_count returns a queryset categories = Category.objects.add_related_count( Category.objects.all(), # Queryset Item, 'category', 'count_collection', cumulative=True, extra_filters={'id__in': UserItems.objects.filter(user_id=userdata.id, listname=UserItems.WISHLIST).values_list('item_id', flat=True )} ).add_related_count( Category.objects.all(), # Queryset Item, 'category', 'count_collection', cumulative=True, extra_filters={'id__in': UserItems.objects.filter(user_id=userdata.id, listname=UserItems.COLLECTION).values_list('item_id', flat=True )} -
Save method is not being called in StackedInline model admin in Django
models.py class form21tablet(models.Model): date = models.DateField() TotalNetWt = models.DecimalField(max_digits=8, decimal_places=3,default=0, editable=False, null=True, blank=True) yieldPercent = models.DecimalField(max_digits=4, decimal_places=2, default=0, editable=False, null=True, blank=True) def save(self): #self.save() print('hello This is Before if') #calculation of total and percentage totnet=0 totgross= 0 # print('Hi', self.form21entry_set.all()) for item in self.form21entry_set.all(): print('Hi') totnet += item.net totgross += item.gros print(totnet) print(totgross) self.TotalNetWt = totnet if totgross: self.yieldPercent = totnet*100/totgross print(self.TotalNetWt) print(self.yieldPercent) super().save() class form21entry(models.Model): formref = models.ForeignKey(form21tablet, on_delete=models.CASCADE) Date = models.DateField() ContainerNo = models.IntegerField() tare = models.DecimalField(max_digits=5, decimal_places=3, verbose_name='Tare Wt.(KG)') gros = models.DecimalField(max_digits=5, decimal_places=3, verbose_name='Gross Wt.(KG)') net = models.DecimalField(max_digits=5, decimal_places=3, verbose_name='Net Wt.(KG)', editable=False) done_by = models.CharField(max_length=50) Checked_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+') answer = ( ('1', 'Ok'), ('0', 'Not Ok') ) Remarks = models.CharField(max_length=50, choices=answer) def save(self): self.net = self.gros - self.tare return super().save() def __str__(self): return str(self.Date) + ' - ' + str(self.ContainerNo) admin.py class form21entryInline(admin.StackedInline): model = form21entry class form21tabletAdmin(admin.ModelAdmin): list_display = ['date', 'TotalNetWt', 'yieldPercent'] class Meta: model = form21tablet inlines = [form21entryInline] readonly_fields = ('TotalNetWt', 'yieldPercent') admin.site.register(form21tablet, form21tabletAdmin) I am trying to get the calculations when I save the form but I am not getting any answers when I save it once, if I save it twice it returns me all the calculations. -
Django : How display the data of a ChoiceFiled Form with the init method
I want to do a form that does a dropdown list and does not depend on a Model. However the data on the dropdown menu depends on the user and the data that the user has access. What should I add to my form to display the data of the init method. forms.py class SelectClient(forms.Form): ID_Customer = forms.ChoiceField() def __init__(self, *args, **kwargs) : self.user = kwargs.pop('user') super(SelectClient, self).__init__(*args, **kwargs) id_client_list = TblAadJntGroupmember.objects.filter(id_aaduser=self.user.id).values_list('id_aadgroup', flat=True) id_client_list = list(id_client_list) self.choices = TblAadGroups.objects.all().filter(id__in=id_client_list) -
django multiple photo upload per entry
I want to let the user upload text, a describtion and multiple images per entry. But at the moment I create a new entry for every photo, instead of having multiple images for one entry. What do I have to change. Thank you. models.py class MultipleImage(models.Model): title = models.CharField(max_length=200) describtion = models.TextField(null=True, blank=True) images = models.FileField() forms.py class CommentForm(forms.ModelForm): class Meta: model = MultipleImage fields = ['title', 'describtion', 'images'] widgets = { 'images': forms.ClearableFileInput(attrs={'multiple': True}), } views.py def upload(request): form = CommentForm() if request.method == "POST": images = request.FILES.getlist('images') for image in images: MultipleImage.objects.create(images=image) images = MultipleImage.objects.all() return render(request, 'index.html', {'images': images, 'form':form}) index.html <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} {{field}} {% endfor %} </form> -
Django models Count and Q methods are throwing type error
I'm trying to generate dynamic query based on user input values. The normal query would be like this. my_model.objects.aggregate(Type1=Count('pk', filter=Q(db_field=1)),Type2=Count('pk', filter=Q(db_field=2)),Type3=Count('pk', filter=Q(db_field=3)),Type4=Count('pk', filter=Q(db_field=4)),Type5=Count('pk', filter=Q(db_field=5))) This is the code I have written for my testing. from django.db.models import (Count, Q) field = field_values # (it's tuple and read from input) aggregate_query = '' if field != None: for j in field: aggregate_query += f"{j[1]}={Count}('pk', filter={Q}(db_field={j[0]}))," my_model.objects.aggregate(aggregate_query[:-1]) the aggregate query is generate correctly and got results when I evaluated on python console. But when I execute this code, its throwing below error. QuerySet.aggregate() received non-expression(s): Type1=<class 'django.db.models.aggregates.Count'>('pk', filter=<class 'django.db.models.query_utils.Q'>(db_field=1)), Type2=<class 'django.db.models.aggregates.Count'>('pk', filter=<class 'django.db.models.query_utils.Q'>(db_field=2)), Type3=<class 'django.db.models.aggregates.Count'>('pk', filter=<class 'django.db.models.query_utils.Q'>(db_field=3)), Type4=<class 'django.db.models.aggregates.Count'>('pk', filter=<class 'django.db.models.query_utils.Q'>(db_field=4)), Type5=<class 'django.db.models.aggregates.Count'>('pk', filter=<class 'django.db.models.query_utils.Q'>(db_field=5)). Can someone help me on this. -
Django Migration in Production [closed]
I have a Django project in production. What would be the best practice in working with migrations? An example I have 3 apps in production, after some time the client needs another app, how to keep the migrations synchronized so it doesn't break. -
Django and HTMX - AttributeError: 'int' object has no attribute 'get'
I'm trying to make this POST call work with Django: <span id="quantity-in-cart">{{item.quantity_in_cart}}</span> <button class="btn btn-success btn-sm" hx-post="/cart/add/1/" hx-target="#quantity-in-cart" hx-swap="outerHTML">+</button> But, when I click the button which performs the POST call, I get this error: Internal Server Error: /cart/add/4/ Traceback (most recent call last): File "/home/neisor/.local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/neisor/.local/lib/python3.9/site-packages/django/utils/deprecation.py", line 119, in __call__ response = self.process_response(request, response) File "/home/neisor/.local/lib/python3.9/site-packages/django/middleware/clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'int' object has no attribute 'get' [22/Mar/2022 12:47:01] "POST /cart/add/4/ HTTP/1.1" 500 66757 I also have this in my template at the end of <body> tag: <script> document.body.addEventListener('htmx:configRequest', (event) => { event.detail.headers['X-CSRFToken'] = '{{ csrf_token }}'; }) </script> Any ideas how to fix it? Thank you -
How to reset Id number after deleting a todo in todo list?
I am working with React and Django. I almost completed it, but when I delete a todo from the list, it is not updating the id number. For example, I have five todos in a list 1, 2,3, 4 and 5. When I delete number 4. It is showing 1, 2, 3, 5. It should be in sequence. It should be like 1, 2, 3 and 4. I hope my question is understandable. Please help me with this issue. My Main Component AddTodo.js import React, { useState, useEffect } from "react"; import { Button, Form } from "react-bootstrap"; import API from "../API"; const AddTodo = () => { const [title, setTitle] = useState(""); const [description, setDescription] = useState(""); const [todoId, setTodoId] = useState(null); const [todos, setTodos] = useState([]); useEffect(() => { refreshTodos(); }, []); const refreshTodos = () => { API.get("/") .then((res) => { setTodos(res.data); }) .catch(console.error); }; const onSubmit = (e) => { e.preventDefault(); let item = { title, description }; API.post("/", item).then(() => refreshTodos()); }; const onUpdate = (id) => { let item = { title }; API.patch(`/${id}/`, item).then((res) => refreshTodos()); }; const onDelete = (id) => { API.delete(`/${id}/`).then((res) => refreshTodos()); }; function selectTodo(id) { let item = … -
Comment utiliser les listes dans le modèle django pour obtenir le diagramme si dessous en pièce jointe [closed]
Je veux créer une liste imbriqués dans une liste de manière à ce que quand on choisit un objet, cela affiche automatique les valeurs que j'ai renseigné dans ma liste Model Django liste imbriqués -
ContentNotRenderedError: The response content must be rendered before it can be accessed (Django Middleware)
I am creating Django middleware for blocking a user when (s)he gets throttled more than 5 times but I am getting ContentNotRenderedError. Full error msg: Traceback (most recent call last): File "/home/raptor/Application/utilities/anaconda3/envs/slic4rapi/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/raptor/Application/utilities/anaconda3/envs/slic4rapi/lib/python3.8/site-packages/django/utils/deprecation.py", line 119, in __call__ response = self.process_response(request, response) File "/home/raptor/Application/utilities/anaconda3/envs/slic4rapi/lib/python3.8/site-packages/django/middleware/common.py", line 113, in process_response response.headers['Content-Length'] = str(len(response.content)) File "/home/raptor/Application/utilities/anaconda3/envs/slic4rapi/lib/python3.8/site-packages/django/template/response.py", line 126, in content raise ContentNotRenderedError( django.template.response.ContentNotRenderedError: The response content must be rendered before it can be accessed. [22/Mar/2022 11:55:03] "GET /api/v1/userdetail/ HTTP/1.1" 500 84321 Middleware class class BlockMiddleware: def __init__(self, get_response): self.get_response = get_response # some other variables def __call__(self, request): # handle_blocking will return "None" if user can access application else "rest_framework.response.Response" object blocking_res = self.handle_blocking(request) if blocking_res: return blocking_res response = self.get_response(request) # logic for counting how many throttles have left # then if throttles_left <= 0: return Response( data='User is blocked due to exceeding throttles limit.', status=status.HTTP_403_FORBIDDEN ) else: return response Example return of handle_blocking function: return Response( data='User is blocked, please contact the support team.', status=status.HTTP_403_FORBIDDEN ) It works when I remove the middleware and don't use the Response class(return the self.get_response(request) instead). I am unable to figure out the error. What am I doing … -
Field is required in the Django Admin even though I have set "blank=True" in the Model
In models.py class DeploymentType(models.Model): deployment_type = models.CharField(primary_key=True, max_length=30, verbose_name="Deployment Type",blank=True) def __str__(self): return self.deployment_type class ActivationType (models.Model) : activation_type = models.CharField ( primary_key=True, max_length=20, verbose_name = "Activation Type" ) permitted_host_methods = models.ManyToManyField( HostMethod, verbose_name = "Permitted Host Methods" ) permitted_deployment_types = models.ManyToManyField( DeploymentType, verbose_name = "Permitted Deployment Types" ) class Meta: verbose_name = "Activation Type" def __str__(self): return str(self.activation_type) But then on the Django admin page, I can't create a new Activation Type without selecting a Permitted Deployment Type. Furthermore, if I go into an existing Activation Type I am not sure how to select zero Permitted Deployment Types. I believe I am using Django 3.1.1 -
Django model methods(Date filter)
Been struggling for weeks now with this issue, starting to feel like I will never solve it. I have these methods under my model. def sfget_totals(self): return self.agent_sale.filter(Date_created__range=["2022-03-01","2022-04-02"]).count() def sfget_confirmed(self): return self.agent_sale.filter(State="Confirmed",Date_created__range=["2022-03-01","2022-04-02"]).count() def sfget_debi(self): return self.agent_sale.filter(AcknowledgeQA=True,State="Confirmed",Debi_status="Accepted",Date_created__range=["2022-03-01","2022-04-02"]).count() def sfget_requested(self): return self.agent_sale.filter(Debi_status="Requested",Date_created__range=["2022-03-01","2022-04-02"]).count() def sfget_cancelled(self): return self.agent_sale.filter(State="Cancelled",Date_created__range=["2022-03-01","2022-04-02"]).count() def sfget_pending(self): return self.agent_sale.filter(State="Pending",Date_created__range=["2022-03-01","2022-04-02"]).count() in the above example i am putting the dates in manually(it works and returns the correct query) problem is I still don't know how to make the user plug these dates in through the site. This is my view. def Team_stats(request,pk): sd = request.GET.get("from") ed = request.GET.get("to") start_date = datetime.datetime.strptime(sd, "%Y-%m-%d").date() end_date = datetime.datetime.strptime(ed, "%Y-%m-%d").date() if start_date == None or end_date == None: sales_agent = SalesAgent.objects.filter(Team_leader=pk) return render(request,"Sales/Team_detail_page.html",{"sales_agent":sales_agent}) else: sales_agent = SalesAgent.objects.filter(Team_leader=pk,agent_sale__Date_created__range=[start_date,end_date]).distinct() print(type(start_date)) return render(request,"Sales/Team_detail_page.html",{"sales_agent":sales_agent}) This is my template. <form method="GET" action="."> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputEmail4">Start date</label> <input type="date" format='%Y-%m-%d' name="from" class="form-control" id="inputEmail4" placeholder="Start Date"> </div> <div class="form-group col-md-6"> <label for="inputEmail4">End date</label> <input type="date" format='%Y-%m-%d' name="to" class="form-control" id="inputEmail4" placeholder="End date"> </div> </div> <button type="submit" class="btn btn-primary">Search</button> </form> <!-- <p>THERE SHOULD BE A GRAPH IN HERE FOR THE AGENTS STATS</p> --> <br> <br> <div class="container"> <table class="table table-dark table-striped table-bordered"> <thead> <tr> <th scope="col">#</th> <th scope="col">Agent Name</th> <th scope="col">Total sales</th> … -
How to display additional data
By default the table should only show the first 10 rows of the dataset, by clicking on a button “Load more” additionally 10 rows should be shown - reloading the page is fine. next page = "https://swapi.dev/api/people/?page=2", my code: import requests from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet from rest_framework import status from rest_framework.response import Response from datetime import datetime from rest_framework import filters from rest_framework.pagination import PageNumberPagination from rest_framework.decorators import action # class StarWarsAPIListPagination(PageNumberPagination): # page_size = 4 # page_size_query_param = 'page_size' # max_page_size = 20 class StarView(APIView): # pagination_class = StarWarsAPIListPagination # filter_backends = (filters.OrderingFilter) # ordering_fields = ('name',) def get(self, request): a = [] page = request.query_params.get('page', 1) url = f'https://swapi.dev/api/people/?page={page}' response = requests.get(url).json() n = response['next'] a.append(n) return Response(response, status=status.HTTP_200_OK) -
How to name Settings model properly in Django?
As we all know the best code style practice to is to name Django models (classes) as singular (Cat, User, Permission, etc.), instead of plural (Cats, Users, Permissions), because it represents the structure of one record of the model. But in case of user settings it become UserSetting. Setting could be interpretted as one key-value pair but we have complete user settings record with multiple key-value pairs. So it's UserSettings. It appearently become confusing. So what should we do in that case? UserSetting UserSettings UserSettingsRecord Other ideas? -
upload a file to a database in Django
I have a button in an HTML file (Upload button): <form method="POST"> {% csrf_token %} <div class="form-group" id="form"> <div class="inputs"> <div style="text-align:center;display:block;"> <input type="submit" id="btnupload" class="button btn btn-primary" value="Upload"> </div> <label for="word1">Word 1</label><br> <input type="text" style="width: 100%;" id="word1" name="word1" placeholder="Enter first word" required><br><br> <label for="word2">Word 2</label><br> <input type="text" style="width: 100%;" id="word2" name="word2" placeholder="Enter second word" required><br><br> <label for="word3">Word 3</label><br> <input type="text" style="width: 100%;" id="word3" name="word3" placeholder="Enter third word" required><br><br> <label for="word4">Word 4</label><br> <input type="text" style="width: 100%;" id="word4" name="word4" placeholder="Enter fourth word" required><br><br> <label for="word5">Word 5</label><br> <input type="text" style="width: 100%;" id="word5" name="word5" placeholder="Enter fifth word" required><br><br> <div style="text-align:center;display:block;"> <input type="submit" id="btnrun" class="button btn btn-primary" name="tp" value="Run"> </div> </div> </div> </form> What I want is that when I click that button upload a CSV file to a DB table that has 5 fields (word1 to word5 and is user attached). I have done something but the button won't work, what am I missing? views.py: def uploadFile(request): if request.user.is_authenticated: if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): usr = User.objects.get(username=request.user) wt = WordsTable() wt.user = usr wt.word1 = form.cleaned_data['word1'] wt.word2 = form.cleaned_data['word2'] wt.word3 = form.cleaned_data['word3'] wt.word4 = form.cleaned_data['word4'] wt.word5 = form.cleaned_data['word5'] wt.save() messages.success(request, "Word added successfully") return redirect("home") context = {'form': … -
What is the command for starting a WSGI server for Django?
I've developed an application in Django that I usually run in development mode: python manage.py runserver I do the same for my deployed instances - obviously a security issue that I now want to resolve. From the Django docs, its not clear to me how to: For simplicity sake, I picked wsgi (over asgi): https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ . From this page, its not clear to me how my 'runserver' command changes to run the wsgi server over the development server. Should I run the wsgi.py file? That doesn't seem to do anything. From the page above, its not clear whether wsgi is actually a server, or more a platform/type of servers. Do I need to use uwsgi/uvicorn/etc. instead? I'm testing on windows - uvicorn is unix only, so I tried uwsgi, but thats giving me this error message: AttributeError: module 'os' has no attribute 'uname' - I guess its Unix only as well So I'm using the docker image I was already building for deployment - uwsgi is giving me issues again because my docker image has no compiler, so I try now with gunicorn. that should be easy: gunicorn project.wsgi, which gives me: ModuleNotFoundError: No module named 'project/wsgi' my folder structure … -
?! I am working on my graduation project and using deep learning to make image segmentation.When I run server this error raise 👇🏼
File "C:\Users\derar\Desktop\GraduationProject\django_faculty_detector\core\views.py", line 2, in from .ai_model import get_faculity_id_from_image_url File "C:\Users\derar\Desktop\GraduationProject\django_faculty_detector\core\ai_model.py", line 17, in from object_detection.utils import label_map_util File "C:\Users\derar\Desktop\GraduationProject\django_faculty_detector\venv\lib\site-packages\object_detection\utils\label_map_util.py", line 21, in from object_detection.protos import string_int_label_map_pb2 ImportError: cannot import name 'string_int_label_map_pb2' from 'object_detection.protos' (C:\Users\derar\Desktop\GraduationProject\django_faculty_detector\venv\lib\site-packages\object_detection\protos_init_.py) -
Django : Display specific attributes of my ModelMultipleChoiceField Form and get the ID from it
I am Newbee in Django, so I have difficulties to write correctly my form and know how to use it. I have a form that displays a dropdown list depending on the user. So it is why I have queries. Below is my form and my models : models.py class UploadFiles(models.Model): Id = models.IntegerField(db_column='ID') # Field name made lowercase. Filename = models.CharField(db_column='FileName', max_length=255, blank=True, null=True) # Field name made lowercase. PreviousFilename = models.CharField(db_column='FileNameBeforeIndex', max_length=255, blank=True, null=True) # Field name made lowercase. User = models.CharField(db_column='User', max_length=255, blank=True, null=True) # Field name made lowercase. SizeFile = models.IntegerField(db_column='Sizefile') Uploaded_at = models.DateTimeField(db_column='Timestamp', auto_now_add=True) # Field name made lowercase. ID_Customer = models.IntegerField(db_column='ID_Customer', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'tbl_PdfPath' class TblAadJntGroup(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. id_aadgroup = models.IntegerField(db_column='ID_AADGroup', blank=True, null=True) # Field name made lowercase. id_aaduser = models.IntegerField(db_column='ID_AADUser', blank=True, null=True) # Field name made lowercase. createdon = models.DateTimeField(db_column='CreatedOn', blank=True, null=True) # Field name made lowercase. createdby = models.CharField(db_column='CreatedBy', max_length=255, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'tbl_AAD_jnt_GroupMember' class TblAadGroups(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. idcustomer = models.IntegerField(db_column='IDCustomer', blank=True, null=True) # Field … -
count the number of times an order has been approved
I have an application that deals with users making an order but anytime an order is made it needs to be approved before it can be issued or sold out. Is there a way to count the number of times an order has been approved? models class Order(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) pro_name = models.ForeignKey(Product, on_delete=models.CASCADE, null=True,related_name='product') user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) order_quantity = models.PositiveIntegerField(null=True) order_status = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=False, auto_now=True, null=True) views.py def order_approve(request, order_id): order = Order.objects.get(id=order_id) order.order_status = 1 order.save() return redirect('dashboard-order') I will be grateful for your response. Thank you -
django bulk_create with Null value
models.py class control(models.Model): amount = models.IntegerField() driver = models.ForeignKey(driver, on_delete=models.CASCADE, null=True, blank=True) views.py controlValues = [ (1,1,1), (2,8,None) ] control.objects.bulk_create([ control( id = i[0], amount = i[1], driver = driver(id = i[2]) ) for i in controlValues], ignore_conflicts=True ) I got error: bulk_create() prohibited to prevent data loss due to unsaved related object 'driver'. How can I set Null for driver? I'm using mysql. -
Django - create zip file dynamically and sent it
I'm using python 3.6 and Django 3.2 I managed to create empty zipfile, but after adding files by "writestr" the files is corrupted. How can I add txt files to this zip? here is my view: import zipfile from django.http import HttpResponse def file_generation(request): response = HttpResponse(content_type='application/zip') zip_file = zipfile.ZipFile(response, 'w') zip_file.writestr("filename.txt", "test_inside file") # this line cause error? zip_file.close() zipfile_name = "files.zip" response['Content-Disposition'] = 'attachment; filename={}'.format(zipfile_name) return response -
List past hours of today with django
How do I create a list of past hours of the day? I tried this but it only gets the past 12 hours, and what if the past hour is from yesterday? past_hours = [] for x in range(12): past_hours.append((date - datetime.timedelta(hours=x))) -
django internationalization is not translated to English on the server. Local is normal
python: 3.6 / 3.8 django: 3.2.3 django internationalization is not translated to English on the server. But LanguageCode is correct. Local is normal. # 国际化语言种类 from django.utils.translation import gettext_lazy as _ LANGUAGES = ( ('en-us', _('English')), ('zh-Hans', _('中文简体')), ) DEFAULT_LANGUAGE = 1 # 国际化翻译文件目录 LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),) def ocr(request): translateWords = {} translateWords["title"] = _("图片转文字") translateWords["clickButtonWord"] = _("一键转文字") translateWords["txtareaPlaceholder"] = _("输出内容...") translateWords["clickCopy"] = _("点击复制") translateWords["numberOfRrecognizedCharacters"] = _("识别输出文字数:") translateWords["copied"] = _("已复制") translateWords["notes"] = _("注意事项:上传图片最大4兆本应用永久免费使用!") translateWords["aboutUs"] = _("联系我们") print(get_language()) return render(request, 'ocr.html', {"translateWords":translateWords, }) xxx.html {% load i18n %} <h4>OCR {%trans "图片转文字" %}</h4> I tried compiling the mo file on the server's direct command line, but it didn't work. is : python manage.py makemessages -l en_us python manage.py makemessages -l zh_Hans python manage.py compilemessages screenshot -
django.db.utils.InterfaceError: connection already closed
Stack: Ubuntu (20.04 LTS) Nginx Postgresql (v13.3) An AWS load balancer sends traffic to the Ubuntu instance(k8s cluster), which is handled by Nginx, which forwards on to Django (4.0.3) running in gunicorn (19.9.0). Django connects to the database using psycopg2 (2.8.6). The issue I have is that the database connection seems to shut down randomly. Django reports errors like this: `InterfaceError: connection already closed File "django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "contextlib.py", line 79, in inner return func(*args, **kwds) File "django/views/generic/base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "django/views/decorators/cache.py", line 62, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "django/views/generic/base.py", line 119, in dispatch return handler(request, *args, **kwargs) File "django/views/generic/detail.py", line 108, in get self.object = self.get_object() File "django/views/generic/detail.py", line 53, in get_object obj = queryset.get() File "django/db/models/query.py", line 492, in get num = len(clone) File "django/db/models/query.py", line 302, in __len__ self._fetch_all() File "django/db/models/query.py", line 1507, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "django/db/models/query.py", line 57, in __iter__ results = compiler.execute_sql( File "django/db/models/sql/compiler.py", line 1359, in execute_sql cursor = self.connection.cursor() File "django/utils/asyncio.py", line 26, in inner … -
Uploading files to Django + Nginx doesn't save it in the media volume in Docker
Basically whenever I try to upload a file using my website, the file doesn't get saved on the media volume. I don't think its a code issue as it works perfectly fine without the container even when paired with nginx. I followed this tutorial to setup my docker containers. Here is my Dockerfile: # pull official base image FROM python:3.9.6-alpine # set work directory WORKDIR /home/azureuser/ecommerce3 # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # fixing alpine related pip errors RUN apk update && apk add gcc libc-dev make git libffi-dev openssl-dev python3-dev libxml2-dev libxslt-dev RUN apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy entrypoint.sh COPY ./entrypoint.sh . RUN sed -i 's/\r$//g' ./entrypoint.sh RUN chmod +x ./entrypoint.sh # copy project COPY . . # running entrypoint.sh ENTRYPOINT ["./entrypoint.sh"] docker-compose.yml: version: '3.8' services: web: build: context: ./ dockerfile: Dockerfile command: sh -c "cd DVM-Recruitment-Task/ && gunicorn DVM_task3.wsgi:application --bind 0.0.0.0:8000" volumes: - static_volume:/home/azureuser/ecommerce3/staticfiles:Z - media_volume:/home/azureuser/ecommerce3/mediafiles:Z - log_volume:/home/azureuser/ecommerce3/logs expose: - 8000 depends_on: - db db: image: …