Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django server throwing a MultiValueDictKeyError even though the value of the parameter is present
I have a Django endpoint that runs a query that updates a row in my database using the image_name. I am storing that image name in the client session storage and retrieving it and sending it to the endpoint. The endpoint then runs the function upload_to_db() on the data and returns success or failure based on the updating of the database. The problem is, this function is continuously throwing me a MultiValueDictKeyError error over the image name specifically in this line: img_name = request.POST["image_name"] Despite this, the function is running and the values get updated as needed but I still get this error. class paymentClass(APIView): def get(self, request): return render(request, "payment.html") def post(self, request): email = request.POST["email"] pid = request.POST["pid"] img_name = request.POST["image_name"] # if not all([email, pid, img_name]): # body = {"errorMessage": "Missing parameters"} # return JsonResponse(body, status=400) result = upload_to_db(email, img_name, pid) print(result) if result == "success": return JsonResponse({"message": "created successfully", "image_name": img_name}, status=201) else: body = {"errorMessage": result} return JsonResponse(body, status=400) I have tried printing the image name, which shows the right name. I have made sure that the image is passed on to the server correctly as well. -
I have a problem with static files in Django. I tried all the configurations and I can't use the cs or js
I'm trying configure the static files and you already tried to do everything but nothing works and I don't know what else to doSTATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] `{% extends 'base.html' %} {% load static %} {% block content %} homa {% endblock %}` .home { background-color: #f0f0f0; padding: 20px; /* Otros estilos aquí */ } solve it and be able to use the static files -
Django admin panel shows field max length instead of field name
I know it is a little bit weird but I see field max length instead of field name in admin panel as below: My model: class SituationFlag(models.Model): name=models.CharField(30) slug=models.SlugField(null=False,blank=True, unique=True,editable=False,max_length=30) description =models.CharField(200) cssclass=models.CharField(30) def __str__(self) -> str: return self.name def save(self,*args,**kwargs): self.slug=slugify(self.name) super().save(*args,**kwargs) Also I'm using that SituationFlag model with many-many relationship in other model as below: class Subject(models.Model): title=models.CharField(max_length=200) description = models.TextField() is_active=models.BooleanField(default=True) slug=models.SlugField(null=False,blank=True, unique=True,db_index=True,editable=False,max_length=255) category=models.ForeignKey(Category,on_delete= models.SET_NULL,null=True) situation_flag=models.ManyToManyField(SituationFlag) def __str__(self) -> str: return self.title def save(self,*args,**kwargs): self.slug=slugify(self.title) super().save(*args,**kwargs) What am I missing here? Any help would be much appreciated. -
Field value not being populated except when it's being debugged
I'm having a weird problem where normally field_val should be set to some particular value but is being set to "". When I debug in vscode and look into the value from the debugger, inspecting it (possibly triggering something), suddenly the variable becomes available. When I'm not debugging the value is empty string. I couldn't understand what's happening here. Is there some kind of lazy evaluation that I'm missing in django forms? I'm trying to keep the submitted value in the datalist when the form submission fails. Trying to take that value from the self.instance which is an instance of my django db model basically. class DatalistFieldMixin: def make_field_datalist(self, field_name, choices, choice_format=lambda c: c): field_val = getattr(self.instance, field_name) or "" # Create the datalist widget while setting the html "value" attribute. # And set the widget as the form field. if self.fields.get(field_name): widget = DatalistWidget( choices=[choice_format(c) for c in choices], attrs={"value": field_val}, ) self.fields[field_name].widget = widget class ObjectAdminForm(DatalistFieldMixin, forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.make_field_datalist( field_name="display_unit_id", choices=BroadsignDisplayUnit.objects.all(), choice_format=lambda c: ( c.display_unit_id, " - ".join((str(c.display_unit_id), c.display_unit_name)), ), ) -
Trouble Sending Data from ESP32 to Django Project on Local Computer
I'm trying to send data from my ESP32 to a Django project deployed on my computer. However, the ESP32 seems cannot fetch the address of Django project, here are details: My computer and ESP32 chip are connected to the same Wi-Fi network. The Django project is running on 127.0.0.1:8000, and I'm attempting to send data from the ESP32 to xxx.xxx.xxx.xxx:8000/suitcase/esp32_test (where xxx.xxx.xxx.xxx is my computer's IP address). However, the ESP32 was unable to successfully transmit data to this address, Django local terminal didn't show anything about ESP32's message. I've tried changing the server address in the ESP32 code to 127.0.0.1:8000, but it apparently didn't resolve the issue. What could be causing this problem and how can I troubleshoot it? The esp32 code: #include <HardwareSerial.h> #include <HTTPClient.h> #include "WiFi.h" #define GPSRX_PIN 16 #define GPSTX_PIN 17 #define GPS_SERIAL Serial2 const String serverAddress = "xxx.xxx.xxx.xxx:8000/suitcase/esp32_test"; void initWiFi(String ssid, String password) { WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); Serial.print("***********Connecting to WiFi .."); while (WiFi.status() != WL_CONNECTED) { Serial.print('.'); delay(1000); } Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); Serial.println(WiFi.RSSI()); } bool HaveUsefulData(String data){ if(data.startsWith("$GNGLL")){ return true; }else{ return false; } } String ExtractProxy(String data){ int commaIndex = data.indexOf(','); if (commaIndex != -1 && data.length() > commaIndex + 13) { … -
file not found with PyInstaller and Django
I'm using PyInstaller for a Django application, with some difficulties I was able to generate the .exe file and the application starts, but when I try to see any page I get TemplateDoesNotExist error. Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\path\to\project\dist\vale_remote\_internal\src\dashboard\templates\dashboard\pages\dashboard.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\path\to\project\dist\vale_remote\_internal\src\interview\templates\dashboard\pages\dashboard.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\path\to\project\dist\vale_remote\_internal\src\vale_remote\templates\dashboard\pages\dashboard.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\path\to\project\dist\vale_remote\_internal\django\contrib\admin\templates\dashboard\pages\dashboard.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\path\to\project\dist\vale_remote\_internal\django\contrib\auth\templates\dashboard\pages\dashboard.html (Source does not exist) If i go to '_internal' folder i see no 'src' folder, I don't know if I have to change the path to the templates or I should create this src folder somehow. In my 'normal' folder structure (not the PyInstaller generated) the template django is looking for is in project/dashboard/templates/dashboard/pages/dashboard.html -
AttributeError: type object 'Task' has no attribute 'models'
It says my object Task has no attribute models, I tried to check if i had anywhere bad case but I don't think i have. views.py: from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib import messages from .forms import CreateTask from .models import Task def Home(request): return render(request, "Home.html") def task_view(request): current_user = request.user.id task = Task.models.all.filter(user=current_user) context = {"task": task} return render(request, "task_view.html") def task_creation(request): form = CreateTask() if request.method == "POST": form = CreateTask(request.POST) if form.is_valid(): task = form.save(commit=False) task.user = request.user task.save() return redirect("/Home/task_view/") context = {"form":form} return render(request, "task_creation.html") models.py: from django.db import models from django.contrib.auth.models import User import datetime class Task(models.Model): title = models.CharField(max_length=100, null=True) description = models.CharField(max_length=5000, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) error block: Django version 5.0.2, using settings 'task_manager.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: /Home/task_view/ Traceback (most recent call last): File "C:\Users\lubos\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lubos\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lubos\OneDrive\Plocha\task_manager\tasks\views.py", line 16, in task_view task = Task.models.all.filter(user=current_user) ^^^^^^^^^^^ AttributeError: type object 'Task' has no … -
CKEditor in React - Upload images correctly, but the editor alerts opposite
The image is correctly send to the server and gets upload, but for some reason the editor shows an alert that says 'Cannot Upload'. This is the React Component where I have the config of CKEditor: import { CKEditor } from "@ckeditor/ckeditor5-react"; import ClassicEditor from "@ckeditor/ckeditor5-build-classic"; const PostEditor = ({ onChange, value }) => { return ( <CKEditor editor={ClassicEditor} config={{ ckfinder: { uploadUrl: "http://127.0.0.1:8000/api/image/list/", }, upload: { dataType: "multipart", }, }} data={value} onChange={(event, editor) => { const data = editor.getData(); // console.log(event); // console.log(editor); console.log(data); onChange(data); }} /> ); }; export default PostEditor; This is the error: CKEditor5 Upload Error The explorer where I selected the image doesn't showed up in the recording. As you can see, the editor make a post request whenever you try to add some image to the post, as it should be, then the image gets uploaded, but the editor can't read the image, I don't know why. Maybe I'm missing some configs so the editor can track the url? It is my first time using CKEditor. Any help would be useful, thanks! Upload images to CKEditor. Images uploaded to backend server and charge them in the post. CKEditor: Upload Error. Although the images were … -
Bokeh, how do i remove datetimes without corresponding values?
hope you are doing well, i would like to render a chart without the long lines present, which correspond to the values that do not have the corresponding pair. Here is the function that is generating my chart, hope i does not scary you: def get(self, request): user=request.user historical_me=FinancialInstrument.objects.all() form = self.form_class(historical_me=historical_me) retrive=HistoricalData.objects.all() get_symbol=retrive.filter(instrument__symbol="BTUSD").order_by('datetime') fields=get_symbol.values('datetime','opening_price','closing_price','min_price','max_price','volume') df=pd.DataFrame.from_records(fields) x_values = [key.datetime for key in get_symbol] y_values = [float(key.opening_price) for key in get_symbol] source = ColumnDataSource(data=dict(dater=x_values,pricer=y_values)) plot = figure(title="New title", width=780, height=400, x_axis_label="Date", y_axis_label="Max Price", x_axis_type="datetime") plot.line(x='dater',y='pricer', source=source,line_width=3) unique_dates = HistoricalData.objects.order_by('datetime').values_list('datetime', flat=True).distinct() plot.line(x='datetime', y='opening_price', source=source, line_width=3) plot.toolbar.autohide = True script, div = components(plot) if user.is_authenticated: return render(request,self.template_name, {'form':form,'days_of_month': [i for i in range(1,32)], 'script':script, 'div':div, }) return redirect('home') ``` This is the chart it produces, i need an approach to suppress those long lines, which correspond to the dates that do not have a corresponding value. [![The corresponding chart have these long lines, which i would line to suppress][1]][1] [1]: https://i.stack.imgur.com/QNreK.png -
TypeError at /signup/ join() argument must be str, bytes, or os.PathLike object, not 'dict'
"def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user=form.save() login(request,user) return redirect(frontpage) else: form=UserCreationForm() return render('core/signup.html',{'form':form})" when ı running this code block ı return a error "TypeError at /signup/ join() argument must be str, bytes, or os.PathLike object, not 'dict'" how can ı fix it? ı wanna make a sign up form -
Django pre-signed url file uploads architecture MVC
I'm trying to implement file uploads using pre-signed URLs using Django. I've got the upload part working, however, I'm not sure what the architecture should look like for standard MVC application. Assume this model: class Document(models.Model): file = models.FileField() extra_field = models.CharField() Render GET page with file upload form. User modifies <input type='file'> and the browser makes a request to /api/get-presigned-url which returns PUT URL for file upload Browser uploads a document to PUT URL. These 3 steps are clear. The next steps are completely unclear and I'm not sure how to then save this already uploaded document to my Document model. If I submit the form with Filefield set - the file is uploaded into server-side which we're trying to avoid using pre-signed URLs. If I modify the form to have file_url and set it to pre-signed PUT URL - it works but it's not secure as user can just modify the file name and access any file in the bucket. What would be the recommended architecture for using pre-signed URLs with Django standard MVC pattern with GET/POST requests. -
ERR_TOO_MANY_REDIRECTS Django-Azure
I'm trying to get an SSO authentication in my django admin app and I have those lines : AZURE_AUTH = { "CLIENT_ID": "xxxxxxxxxxxxxxxxxxxxx", "CLIENT_SECRET": "xxxxxxxxxxxxxxxxxxx", "REDIRECT_URI": "http://localhost:8000/admin", "SCOPES": [""], "CA_BUNDLE": "false", "AUTHORITY": "https://login.microsoftonline.com/450c4b37-1c5f-4415-a413-c83c13fd5316/", # "PUBLIC_URLS": ["<public:view_name>",] # "PUBLIC_PATHS": } LOGIN_URL = "/azure_auth/login" AUTHENTICATION_BACKENDS = ("azure_auth.backends.AzureBackend",) But when I put my localhost URL I have a lots of redirects in my terminal and I cannot connect to my SSO account because of too many redirects, and yes i tried to disable cookies :( Does this happened to anyone? Let me know if you've any idea -
connect to external ip with port from django deployed on docker
I have django application with mariadb connect with zk terminal via pyzk liberiry , application work fine with local but whe deployed tht with docker and every functionality work fine until start connect with zk terminal I have error Exception: can't reach device (ping 41.32.196.3) application will work with ubuntu and windows zk tirminal must connect py ip and port (4370) docker-compose.yaml version: "3.9" services: db: image: mariadb:10.5 restart: unless-stopped command: - --default-authentication-plugin=mysql_native_password env_file: - ./.env ports: - 3308:3306 container_name: "djanzk_db" build: context: ./mysql dockerfile: Dockerfile web: build: . container_name: "djanzk_web" command: sh -c "python3 manage.py migrate --noinput && python3 manage.py collectstatic --noinput && python manage.py runserver 0.0.0.0:8040" ports: - "8040:8040" extra_hosts: - "host.docker.internal:host-gateway" volumes: - .:/app - /tmp/app/mysqld:/run/mysqld depends_on: - db env_file: - ./.env networks: - default #networks: # outside: # external: true .env # Django settings SECRET_KEY= DEBUG=True DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 0.0.0.0 [::1] # MySQL settings MYSQL_DATABASE=djaznzk MYSQL_USER=root MARIADB_ROOT_PASSWORD=root MYSQL_PASSWORD=root MYSQL_PORT=3306 MYSQL_HOST=db Dockerfile FROM ubuntu:latest LABEL authors="ibralsmn" ENTRYPOINT ["top", "-b"] # Use an official Python runtime as a parent image FROM python:3.10 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set the working directory WORKDIR /app # Install dependencies COPY requirements.txt /app/ RUN pip install -r … -
My website is not showing up after uploading my project to cpanel
I have uploaded my django project as a zip file and extracted in the home directory of the root server. My website is showing up without the images and the css design files. https://www.hightech-metrology.com The root directory of my webpage in remote server is above. In every app inside the project, there is seperate static and template files as shown in the django documentation. But I am having issue with showing the images and css design files for the project. After the quick research I have done, I realized that I should put the images and css files to the public_html file in the root directory. Can anyone help me out with the issue ? For example, the about page's directory is provided below. -
passenger_wsgi.py not responding while deploying django project on cpanel
I am trying to deploy my django project on cpanel for the first time. The problem I am dealing with is that when I create a python app in cpanel, the passenger_wsgi.py file is created but does not run as expected. These are the steps I have taken so far: first I cloned my project then I started to setup a python application from cpanel a passenger_wsgi.py file and two folders named temp and public are now created in my project directory(as you can see in the screenshot). (https://i.stack.imgur.com/hEZeI.png) As I saw in youtube videos, in this step I must be able to see a message in my web url saying: it works! python x.y.z (https://i.stack.imgur.com/QmT63.png) but it does not show this message and only error 403 is retrieving (you can see the response in the screenshot) -
Latency in video streaming from backend to frontend (and vice versa)
I am building a mobile app in flutter X firebase, with the backend in Django. The issue is, my Computer vision algorithm is on the front end, and it sends live key points to the backend where the classifier classifies, and sends the result back to the frontend. This is causing a huge delay of 200ms+. How can I fix this? I tried the CV algo on the frontend, and classifier on the backend to reduce the complexity of the server side. But im out of ideas now. Please let me know if establishing a websocket would help me achieve the desired goals. Also, I wanted to know if i could host the algo on a server rather then using the client's mobile's computation power to reduce the latency. Please note that i am in dire of reducing the latency. All answers are appreciated, thanks! -
Stop Exasol sessions with sqlalchemy+django querries
I have Django endpoint that retreive data from Exasol DB using sqlalchemy. It looks as simple as that: @api_view(['GET']) def exasol_data_view(request): *** engine = create_engine(connection_string) Session = sessionmaker(bind=engine) with Session() as session: result = session.execute(query) data = result.fetchall() session.close() I want to implement a feature where the system cancels a request whenever the user calls the same endpoint repeatedly. This will prevent Exasol from accumulating a large queue of pending requests when a user repeatedly clicks the 'request' button. I tried multiple options including session.close(), close_all_sessions(), and so on. Additionally, engine.poop.status() always gives info that I have only 1 connection. P.S. I'm not allow to send row sql request with KILL SESSION -
How to raise a ValidationError in the ModelForm's save method in Django?
I want my ModelForm error handler to show validation errors from the save() method just like they do in the clean() method - i.e. as a warning on the admin form, instead of generating a 500 page. The code flow is as follows, in admin.py: class XForm(ModelForm): def save(self, **kwargs): super().save(**kwargs) try: self.instance.update_more_stuff_based_on_extra_fields_in_the_form() except IntegrityError: raise ValidationError(_("Earth to Monty Python.")) return self.instance class XAdmin(admin.ModelAdmin): form = XForm admin.site.register(X, XAdmin) This results in a debugger's 500 page when the validation error is triggered, not the preferred admin warning. Note: The following question addresses the similar problem of raising a validation error within the model's save method. Here we want to raise the error in the model form's save method. -
Weasyprint - Django, how to disable header / footer
Good day, I have a problem, I'm creating a pdf Api and I need to disable the header. view : @api_view(["GET", "POST"]) def test(request): # Renderizar la plantilla HTML con los datos # datos = json.loads(request.body) datos = {"name": "pedro"} context = { "STATIC_URL": settings.STATIC_URL, } query = Personas.objects.filter(name=datos.get("name")).values()[0] query = ( ) context.update({ "query" : query }) html_template = render_to_string( "pdfs_templates/Certificado Servicio.html", context ) template {% load static %} {% block content %} <!DOCTYPE html> <html> <head> <style type="text/css" media="all"> @page { /* size: A4 portrait; /* can use also 'landscape' for orientation */ margin: 20px 1cm; /* Margen de la página */ } table, th, td { border: 1px solid black; } .table1-cont { width: 95%; margin-top: 15px; } .tac { text-align: center; } .table-r1 { width: 30%; } .table-r2 { width: 70%; } #content { background-color: red; height: 600px; } tbody, tr, td { /*border: none;*/ } </style> </head> <body> {% include 'pdfs_templates/head.html' %} <div> <div> <label class="txt-lb-3" for="">La Dirección General de Haberes/ o Área Responsable de la Liquidación de haberes extiende el presente certificado</label> </div> <div id="content"> <div class="tac"> <div class="table1-cont"> <table> <tbody> {%for q in query %} <tr> <td class="txt-lb-3 table-r1">{{q.0}}</td> <td class="txt-lb-3 table-r2">{{q.1}}</td> </tr> … -
OSError [Errno 101] Network is unreachable, when trying to send Email in Django using smtplib on GoDaady Server
I have a strange issue. I have a Payment app in Django, deployed on GoDaddy. In app, I need to send email to the user when their payment is successful. I am using smtplib and email libraries. The steps I did are: Created Application Password in Google Account Used my email, that app password, 587 port and smtp.gmail.com server The problem is, it totally works fine on my local host and I receive the email. But, it is not working on GoDaddy and I receive the following error: [Errno 101] Network is unreachable Traceback (most recent call last): File "/home/g549hesohwxf/public_html/pl_payment_gateway/app/utils.py", line 52, in send_email with smtplib.SMTP(smtp_server, smtp_port) as server: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/alt/python311/lib64/python3.11/smtplib.py", line 255, in __init__ (code, msg) = self.connect(host, port) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/alt/python311/lib64/python3.11/smtplib.py", line 341, in connect self.sock = self._get_socket(host, port, self.timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/alt/python311/lib64/python3.11/smtplib.py", line 312, in _get_socket return socket.create_connection((host, port), timeout, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/alt/python311/lib64/python3.11/socket.py", line 851, in create_connection raise exceptions[0] File "/opt/alt/python311/lib64/python3.11/socket.py", line 836, in create_connection sock.connect(sa) OSError: [Errno 101] Network is unreachable I searched around the web and got to know that many hosts block this ports by default to avoid spamming. I tried talking to GoDaddy support. They said following things: GoDaddy does not block … -
Django Model Auto Translation
I have a website in Django. All the static text in the website ( include the admin ) is available in 3 different languages and the user can switch between them. I also have a model in the website called Product with the fields name and description. This is how the product would be saved within the database: product_name = Headphones product_description = Ordinary headphones Is there any way/ library that can automatically translate the field values for each Product object depending on the language chosen? -
Getting CSRF 403 error with django server and nexjs client
I am sending requests to Django server from next.js but I am getting error :403 Forbidden (CSRF cookie not set.), even after sending the csrf token. I am running both Django server and next.js locally. Requesting to same api from postman/insomnia works perfectly fine but not with my next.js app. I did some digging and found it may be issue with CORS, so I did some changes in settings.py but still getting same error. Please help me understand what is going wrong, how I can debug, and what changes should I make. First, I fetch CSRF token using another API which works fine. Then in second api, I add my CSRF token. fetching in Next.js const uploadFile = async () => { // Select file from input element or any other method const fileInput = document.getElementById('fileInput'); const file = fileInput.files[0]; const form = new FormData(); form.append("image", file); const options = { method: 'POST', headers: { cookie: 'csrftoken=2V7dKpZXLN24pLDdDkub9GxM2ljzI0nI', 'Content-Type': 'multipart/form-data; boundary=---011000010111000001101001', 'X-CSRFToken': '2V7dKpZXLN24pLDdDkub9GxM2ljzI0nI' } }; options.body = form; fetch('http://127.0.0.1:8000/getinfo', options) .then(response => response.json()) .then(response => console.log(response)) .catch(err => console.error(err)); }; my settings.py in Django : # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = … -
How can I delete a holiday from a person in vue.js?
I am new to vue.js and I make a project with vue.js and django I write this code in vue.js <i class="mdi mdi-trash-can" @click.prevent="confirm(holiday.id)" ></i> deleteHoliday(holidayID){ setTimeout(()=>{ session.delete(`api/person/${this.$route.params.id}/holiday/${holidayID}/actions/`).then(()=>{ this.fetchPersonHolidays(); }); this.drawerMsg = ""; },5000); }, confirm(holidayID){ Swal.fire({ title: "", text: "", icon: "warning", showCancelButton: true, confirmButtonColor: "#34c38f", cancelButtonColor: "#f46a6a", confirmButtonText: "" }).then((result)=>{ if (result.value){ eventCreate(`${holidayID}`, 3) this.deleteHoliday(holidayID) Swal.fire( "", "success" ); } }); And in django I write this in url file path('api/person/<int:pk>/holiday/<int:id>/actions/', PersonHolidaysActionsView.as_view()) And in views.py file this: class PersonHolidaysActionsView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [permissions.IsAdminUser] serializer_class = PersonHolidaysSerializer queryset = PersonHoliday.objects.all() But I can't delete the holiday of the person. -
Gunicorn Freeze issue
I'm encountering a problem with Gunicorn freezing. I'm hosting a Django application using Docker with Nginx as the web server container and Gunicorn as the application server. The Django instance is replicated in three instances with the following Gunicorn configuration. # gunicorn_config.py worker_class = "gevent" bind = "0.0.0.0:8000" workers = 1 worker_connections = 10 max_requests = 1000 max_requests_jitter = 50 # Request timeout (adjust as needed) timeout = 200 # 30 seconds # Log settings accesslog = "-" # Log to stdout errorlog = "-" # Log to stderr loglevel="debug" # Preload the application before forking worker processes preload = True gunicorn -c gunicorn_config.py django_app.wsgi:application Sometimes, my Gunicorn workers freeze and don't accept any incoming requests. In the Gunicorn log, the message shows the worker stops with signal 9 EPIPE. I can't seem to find the issue. It works fine after I restart the Django containers, same issue occurs after sometime. Meanwhile, I encountered an error on the Redis side: "BusyLoadingError: Redis is loading the dataset in memory." Redis is used for Celery broker, Django channels, and Django caching. Could Redis be the reason for the issue? Package versions: ------------ django = "3.2.12" celery = "5.1.2" redis = "^4.4.1" channels-redis … -
Django MSSQL trying to connect with some arbitrary schema rather than dbo
I am deploying a Django service for a client on their Azure env. When switching the DB connector to their Azure SQL DB I get the following error: django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The specified schema name "b96c7a94-5645-4f7d-ab79-b42d99373823@2fc13e34-f03f-498b-982a-7cb446e25bc6" either does not exist or you do not have permission to use it. (2760) (SQLExecDirectW)')) This is weird, becuase I have not specified any schema name in Django, and dbo schema does exists in the client DB. For example I am able to run a python script with simple queries like this: SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = 'dbo' or CREATE TABLE dbo.Example_test ( ID INT PRIMARY KEY, Name VARCHAR(50), Age INT ) I tried specifing the schema to dbo in the setting like this: DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': NAME, # Initial Catalogue 'USER': USER, # Azure Client Id 'PASSWORD': PASSWORD, # Secret Key 'HOST': HOST, # Data Source 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'extra_params': 'Authentication=ActiveDirectoryServicePrincipal', 'options': '-c search_path=dbo' }, } } but then I get this error: django.db.utils.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL …