Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to send a JSON file from a windows service to a Django web site?
Me and my colleagues are trying to create a windows service which sends battery information and other information in the form of JSON files from a client PC to a Django web site where it will be recorded. What is the best approach for this? and also how do I receive it on the Django web site's side? I am completely new to windows services. Currently we have created a windows service which gives us the JSON file on the client computer itself, but we need to make it so that the file is sent to the Django web server. -
Should I use Django's `FloatField()` or `DecimalField(`) for audio length?
Using duration = float(ffmpeg.probe(audio_path)["format"]["duration"]), I collect an audio/video's length and want to store it using my models. Should I use models.DecimalField() or models.FloatField()? I use it to calculate and store a credit/cost in my model using credit = models.DecimalField(max_digits=20, decimal_places=4) -
Django filter across multiple model relationships
Let a simplified version of my models be as follows: class Order (models.Model): customer = models.ForeignKey("Customer", on_delete=models.RESTRICT) request_date = models.DateField() price = models.DecimalField(max_digits=10, decimal_places=2) @property def agent_name(self): assignment = Assignment.objects.get(assig_year = self.request_date.year, customer = self.customer) if assignment is not None: return assignment.sales_agent.name + ' ' + assignment.sales_agent.surname else: return 'ERROR' class Company (models.Model): pass class Customer (Company): pass class Assignment (models.Model): assig_year = models.PositiveSmallIntegerField() customer = models.ForeignKey("Customer", on_delete=models.CASCADE) sales_agent = models.ForeignKey("Agent", on_delete=models.CASCADE) class Employee (models.Model): name = models.CharField(max_length=32) surname = models.CharField(max_length=32) class Agent (Employee): pass In one of my views, I am displaying all orders by listing their corresponding sales agent, customer, date and price, as follows: def GetOrders(request): orders = Order.objects.order_by('-request_date') template = loader.get_template('orders.html') context = { 'orders' : orders, } return HttpResponse(template.render(context,request)) where orders.html looks something like this: <!DOCTYPE html> <html> <head> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <main> <table> <thead> <th>Agent</th> <th>Customer</th> <th>Date</th> <th>Price</th> </thead> <tbody> {% for x in orders %} <td>{{ x.agent_name }}</td> <td>{{ x.customer.name }}</td> <td>{{ x.request_date }}</td> <td>{{ x.price }}</td> </tr> {% endfor %} </tbody> </table> </main> </body> </html> Now I would like to add some filtering capability to the html in order to select only those sales agent I'm interested in, but this … -
Docker Django mysql
Here's folder structure: 📄 Dockerfile 📄 .env 📄 requirements.txt 📁 pr/ 📁 static/ 📄 app.js 📄 manage.py 📁 pr/ 📄 wsgi.py 📄 __init__.py 📄 urls.py 📄 settings.py 📄 asgi.py 📄 docker-compose.yml Here the important file's content Dockerfile --------- # Use an official Python runtime as a parent image # syntax=docker/dockerfile:1 FROM python:3.11 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Install system dependencies RUN apt-get update \ && apt-get install -y --no-install-recommends \ gcc \ libmariadb-dev \ && rm -rf /var/lib/apt/lists/* # Upgrade pip RUN pip install --upgrade pip # Set the working directory WORKDIR /app # Install Python dependencies COPY requirements.txt /app/ RUN pip install -r requirements.txt # Copy the project code into the container COPY ./pr /app/ # Expose the Django development server port EXPOSE 8000 requirements.txt --------- psycopg2>=2.8 asgiref==3.8.1 Django==5.1.1 djangorestframework==3.15.2 mysqlclient==2.2.4 python-dotenv==1.0.1 sqlparse==0.5.1 pytz==2024.2 settings.py: .... # Database # https://docs.djangoproject.com/en/5.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get('MYSQL_DATABASE'), 'USER': os.environ.get('MYSQL_USER'), 'PASSWORD': os.environ.get('MYSQL_PASSWORD'), 'HOST': 'dj1_mariadb', 'PORT': 3306, } } .... docker-compose.yml: services: dj1_mariadb: image: mariadb:latest container_name: dj1_mariadb restart: always environment: MYSQL_ROOT_PASSWORD: myrpass MYSQL_DATABASE: dj1 MYSQL_USER: ab_usr MYSQL_PASSWORD: mypass volumes: - ./data/mariadb:/var/lib/mysql # apt-get update && apt-get install -y mariadb-client networks: - app-network dj1_pma: … -
Django serializer returning empty array
I have minimal experience with Python, and no experience with Django, but I have been tasked with fixing a bug in a Django app. I have the following models ` class SurveyResponse(models.Model): survey = models.ForeignKey(to=Survey, on_delete=models.CASCADE, related_name="responses") # Don't want to clear out surveys if the mission is cleared. Still may be valuable mission_run = models.ForeignKey(to=MissionRun, on_delete=models.SET_NULL, blank=True, null=True, related_name="survey_responses") grade = models.CharField(max_length=15, blank=True, null=True) # grade level gender = models.CharField(max_length=15, blank=True, null=True) # gender selection race = models.CharField(max_length=50, blank=True, null=True) # race selection exported_survey_file = models.ForeignKey(to="SurveyVendorFile", null=True, blank=True, on_delete=models.SET_NULL, related_name="survey_responses") exported_evaluator_file = models.ForeignKey(to="EvaluatorFile", null=True, blank=True, on_delete=models.SET_NULL, related_name="survey_responses") class SurveyResponseAnswer(models.Model): survey_response = models.ForeignKey(to=SurveyResponse, on_delete=models.CASCADE, related_name="answers") survey_question = models.ForeignKey(to=SurveyQuestion, on_delete=models.CASCADE, related_name="answers") answers = ArrayField(models.CharField(max_length=100), null=True, blank=True) answer = models.CharField(max_length=100, null=True, blank=True) @property def reverse_coding(self): return self.survey_question.reverse_coding` and then this code to serialize a response to a POST request ` class SurveyResponseViewSet(mixins.CreateModelMixin, GenericViewSet): queryset = app_models.SurveyResponse.objects.all() permission_classes = [] serializer_class = app_serializers.SurveyResponseCreateSerializer class SurveyResponseAnswerCreateSerializer(serializers.ModelSerializer): survey_question_id = serializers.IntegerField() answers = serializers.SerializerMethodField(required=False) def get_answers(self, obj): return obj.answers if obj.answers else [] class Meta: model = app_models.SurveyResponseAnswer exclude = ["survey_response", "survey_question"] class SurveyResponseCreateSerializer(serializers.ModelSerializer): survey_id = serializers.IntegerField() answers = SurveyResponseAnswerCreateSerializer(many=True) mission_run_id = serializers.IntegerField() def create(self, validated_data): answers = validated_data.pop("answers", []) survey_response = app_models.SurveyResponse.objects.create(**validated_data) for answer in … -
Django: using sqlsequencereset programmatically inside a custom command
I am trying to create a custom command on Django, which will use the sqlsequencereset command for a list of app labels inside a loop, the idea is to run this command to generate and run the sequence setval query for each table of the app. My implementation: for app_label in app_labels: output = call_command("sqlsequencereset", app_label) with connection.cursor() as cursor: cursor.execute(output) I read inside the Django Documentation that raw queries inside cursor.execute do not support transactions, so i customized the SQL string to not include BEGIN and COMMIT keywords, but it still throws the following syntax error: File "/home/python/.local/lib/python3.12/site-packages/django/db/backends/utils.py", line 122, in execute return super().execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/python/.local/lib/python3.12/site-packages/django/db/backends/utils.py", line 79, in execute return self._execute_with_wrappers( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/python/.local/lib/python3.12/site-packages/django/db/backends/utils.py", line 92, in _execute_with_wrappers return executor(sql, params, many, context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/python/.local/lib/python3.12/site-packages/django/db/backends/utils.py", line 100, in _execute with self.db.wrap_database_errors: File "/home/python/.local/lib/python3.12/site-packages/django/db/utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/python/.local/lib/python3.12/site-packages/django/db/backends/utils.py", line 103, in _execute return self.cursor.execute(sql) ^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.ProgrammingError: syntax error at or near " LINE 1: BEGIN; -
Overriding queryset in Django Admin without effects
Sorry if I'm repetitive on a widely discussed topic, but I can't figure out where the error is, since debug returns the correct result, but the page in the browser does not. In short, I'm implementing an app that is multi-user and multi-tenant, with the use of the django-organizations module. Each model that identifies particular resources has a 'gruppo' field, Foreign Key to the specific tenant. Furthermore, the session contains the tenant('gruppo_utente') in use, in order to allow the change of one tenant to another simply by changing the data stored in the session. request.session['gruppo_utente']=int(tenant) # =gruppo_id This is the model: //model.py from multigroup.models import Gruppo, GruppoUser from mptt.models import MPTTModel, TreeForeignKey class ContoCOGE (MPTTModel): gruppo = models.ForeignKey(Gruppo, on_delete=models.CASCADE, related_name='contoCOCGE_gruppo') nome = models.CharField(max_length=2,default='') descrizione = models.CharField("Descrizione",max_length=50,default='') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['nome'] class Meta: verbose_name = "Conto" verbose_name_plural = "Conti" def antenati(self): tmp='' if self.is_root_node(): return format_html(f'<b> {{}} - {{}} </b>', mark_safe(self.nome), mark_safe(self.descrizione)) for i in self.get_ancestors(): tmp += i.nome + '.' return tmp+self.nome+' - '+self.descrizione antenati.allow_tags = True def __str__(self): tmp='' if self.is_root_node(): return format_html(f'<b> {{}} - {{}} </b>', mark_safe(self.nome), mark_safe(self.descrizione)) for i in self.get_ancestors(): tmp += i.nome + '.' return tmp + … -
(1452, 'Cannot add or update a child row: a foreign key constraint fails ). with data matching in the target table
I I have a django service that interacts with a mysql database that I first developed locally, here no problem however once the database is recreated online on an o2switch server, the foreign key constraints no longer work and I can't understand why, I tried to insert a row in the table 'nomchamp' with data existing in the parent table con but this still returns me the error (1452, 'Cannot add or update a child row: a foreign key constraint fails (goqo5870_lddb.nomchamp, CONSTRAINT nomchamp_ibfk_1 FOREIGN KEY (IDCon) REFERENCES con (ID))'). error raise by django I tried this command in phpmyadmin : INSERT INTO nomchamp(IDCon, NOM) VALUES (1, 'PROSPECT'); and this raise the same error I dont understand. ID in table con So the error is caused by the database not by django but I dont know why this error occurred, I create the database with a sql dump file of my local database. -
Django AJAX: Passing form CSFR verification without proper token attachment. Why?
I have a small Django 5.1.1 project, in which I use AJAX request to submit form data data. I'm using {% csrf_token %} and have the setup for attaching the form csrfToken to the xhr header. PROBLEM: The CSFR verification is SUCCESSFUL even when xhr.setRequestHeader('X-CSRFToken', csrfToken); is commented out. AJAX request goes through and gets the response. It only fails when the {% csrf_token %} is missing. From what I understand it should fail without the form csfrToken attached to the header. What am I missing here? Simplified code: <form id="form1" method="post" class="..."> {% csrf_token %} <div> <label for="A" class=""></label> <input type="text" name="symbol" id="A" class="..."> </div> <div> <button type="submit" id="submit-button"></button> </div> </form> document.getElementById('form1').addEventListener('submit', function(event) { event.preventDefault(); const xhr = new XMLHttpRequest(); const formData = new FormData(this); const csrfToken = this.querySelector('[name=csrfmiddlewaretoken]').value; xhr.open('POST', '/form-submit', true); // xhr.setRequestHeader('X-CSRFToken', csrfToken); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.send(formData); }); def index_view(request): return HttpResponse("", status=200) MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] -
Djnago websocket program which accept the send-all message and send-each message
I have React UI like this, simply it accepts the message from server. import React,{useState,useRef,useEffect,createRef,forwardRef,useImperativeHandle,useContext,RefObject} from 'react'; const WebSocketPage = forwardRef((props,ref) =>{ const webSocketRef = useRef(null); const [messages,setMessages] = useState([]); useEffect(() =>{ if ( webSocketRef.current && webSocketRef.current.readyState === WebSocket.OPEN ) { return; } webSocketRef.current = new WebSocket(`ws://127.0.0.1:8000/ws/chat/`); console.log("websocket",webSocketRef.current); console.log("websocket state",webSocketRef.current.readyState); const onOpen = () => { console.log("WebSocket Connected"); }; const onMessage = (e) => { const data = JSON.parse(e.data); setMessages((messages) => [...messages, data.message]); }; const onError = (e) => { console.log("WebSocket Error: ", e); }; const onClose = () => { console.log("WebSocket Disconnected"); }; webSocketRef.current.addEventListener("open", onOpen); webSocketRef.current.addEventListener("message", onMessage); webSocketRef.current.addEventListener("error", onError); webSocketRef.current.addEventListener("close", onClose); return () => { if (webSocketRef.current?.readyState === 1) { webSocketRef.current.removeEventListener("open", onOpen); webSocketRef.current.removeEventListener("message", onMessage); webSocketRef.current.removeEventListener("error", onError); webSocketRef.current.removeEventListener("close", onClose); webSocketRef.current?.close(); } }; },[]); return( <div>test test</div>) }); export default WebSocketPage then, in the python/django server , I can send the data to UI. def handle(self, *args, **options): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'chat', { "type": "chat_message", "message": {"content":"mytestdada","id":20} } ) It works, and It sends the messages to the every browsers. Now, I am a bit confused. When there is people (A,B,C,D,E) How can I proper use of channel_layer? channel_layer.group_send should be use for sending all people?(A,B,C,D,E) channel_layer.send should be used … -
Why do I keep getting an ModuleNotFound error everytime I runserver in the cmd terminal
I was following a django tutorial for a project but I keep getting an error everytime I runserver and this error began showing up when I added the app to the settings.py of the django project. What do I do to bypass this I tried restarting my work in new terminals and I started over in general but I still ran into the same error -
How to handle Parallel GitHub Actions and Migrations in Django + React Projects
I'm working on a Django + React project, and we use GitHub Actions for CI/CD. The typical workflow when a pull request is raised involves running Selenium tests, which require a large dataset in the database to execute effectively. Once the tests pass, I merge the branch, triggering an AWS CodePipeline that goes through source, manual approval, and deployment stages. The problem I'm facing is related to database migrations when multiple developers raise pull requests simultaneously. If I run the workflows in parallel, I end up with migration conflicts that cause issues down the road. However, if I run the workflows sequentially, the deployment process gets delayed, especially when there are several pull requests in the queue. Current Setup GitHub Actions- Runs on pull requests, runs Selenium tests, and applies migrations to a testing database. AWS CodePipeline- After tests pass and PR is merged, it handles manual approval and deployment to production. Database- I'm using a large dataset, and migrations are applied to both a testing database and the live database in different stages. Concerns Migration Conflicts- When workflows run in parallel and developers raise pull requests with migration changes, I face conflicts when these workflows try to run migrations … -
Font awesome preload warning when Django app deployed to Heroku, but not on dev server
It's my first day using heroku to deploy my Django app. When I deploy my Django app on Heroku, the chrome inspector gives this warning: The resource https://ka-f.fontawesome.com/releases/v6.6.0/webfonts/free-fa-solid-900.woff2 was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate as value and it is preloaded intentionally. When I click the warning link it shows the first line of my index page html, which is blank. I don't get this warning when running in my development server and setting the Django project Debug mode has no effect. I have deleted every mention of fontawesome in my project including removing the fontawesome reference from the head of my base.html and removing it from my installed apps etc., but I still receive this warning. I used search to double check there were no font awesome references. Have tried to look up solutions for several hours today and am stumped. My base.html page looks like this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Dotstory</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="shortcut icon" type="image/x-icon" href="{% static 'storymode/images/favicon.png' %}"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> </head> and my index looks like … -
Django: GET /getMessages// HTTP/1.1" 404 2987
I am following a Django tutorial video on how to create a simple chat room. When I want to create a new room, a pop-up alert says "An error occurred". Couldn't figure out what went wrong. Errors: home.html room.html urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('<str:room>/', views.room, name='room'), path('checkview', views.checkview, name='checkview') > ] views.py from django.shortcuts import render, redirect from chat.models import Room, Message # Create your views here. def home(request): return render(request, 'home.html') def room(request, room): return render(request, 'room.html') def checkview(request): room = request.POST['room_name'] username = request.POST['username'] if Room.objects.filter(name=room).exists(): return redirect('/'+room+'/?username='+username) else: new_room = Room.objects.create(name=room) new_room.save() return redirect('/'+room+'/?username='+username) models.py from django.db import models from datetime import datetime # Create your models here. class Room(models.Model): name = models.CharField(max_length=1000) class Message(models.Model): value = models.CharField(max_length=1000000) date = models.DateTimeField(default=datetime.now, blank=True) user = models.CharField(max_length=1000000) room = models.CharField(max_length=1000000) -
How to Link Multiple Social Accounts to a Single User in Django Allauth with a Custom User and Company Model?
I'm working on a Django project where I want to authenticate users using multiple social accounts and link them to a single account in my custom models. I'm using django-allauth for social authentication, and I have a custom User model along with a Company model. The Company model has a ForeignKey to the User model. The goal: I want a user to be able to log in using multiple social accounts (e.g., Google, Facebook) but all these accounts should link to the same user in my Company model. Essentially, the user should be able to authenticate through different providers but still map to a single User account in my system. My setup: Django version: 4.x django-allauth version: 0.44.x I have a custom User model. Company model has a ForeignKey to the User model. What I need help with: How do I configure django-allauth to allow a single user to authenticate via multiple social accounts and link them to the same User record? How can I ensure that all authenticated social accounts point to the same user, while still linking them to the Company model? 3)Are there any specific settings in django-allauth or middleware changes needed to make this work? I’ve … -
How to get more info on what field differences where found by manage makemigrations
Occasionally when running manage makemigrations in my Django project, I end up with an unexpected migrations.AlterField() entry in my migrations file. I am aware that these result from Django seeing differences between that field's definition in my model and the field's definition after applying all migrations. Is there any way to find out which difference it sees? I can look at my fields in the models and use _meta to get field settings I didn't explicitly specify, but is there any way to get information on what the field looks like on the migrations side of things? Compare the target vs actual state, so to speak? The info I am looking for is, if there is for instance an AlterField() on an IntegerField, that's been picked up because the max value changed, or it has a different verbose_name. For now I just manually dig through the migration files for mentions of that respective field, but I am working with a legacy project that has a LOT of them. So I am wondering if anyone ever ran into the same problem and found a better solution. -
The fixtures are not loaded and says they are not found, although they are there
In django I have folder with fixtures\goods\categories.js and fixtures\goods\products.js. I installed postgreSQL and I have tables categories and products. But when I write "python manage.py loaddata fixtures/goods/categories.json" it appears to me: "CommandError: No fixture named 'categories' found." How do I load fixtures? This may be due to the fact that I may have previously loaded everything into something other than the environment. That is, I did python manage.py dumpdata not in the environment... -
RuntimeError: populate() isn't reentrant how to debug that?
[Wed Sep 11 06:36:45.997990 2024] [wsgi:error] [pid 1043:tid 1147] [remote 49.228.84.26:9457] Traceback (most recent call last): [Wed Sep 11 06:36:45.998052 2024] [wsgi:error] [pid 1043:tid 1147] [remote 49.228.84.26:9457] File "/home/newsroom.dinsordesign.com/wsgi_web/wsgi_web/wsgi.py", line 22, in [Wed Sep 11 06:36:45.998063 2024] [wsgi:error] [pid 1043:tid 1147] [remote 49.228.84.26:9457] application = get_wsgi_application() [Wed Sep 11 06:36:45.998075 2024] [wsgi:error] [pid 1043:tid 1147] [remote 49.228.84.26:9457] File "/home/newsroom.dinsordesign.com/venv/lib64/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Wed Sep 11 06:36:45.998084 2024] [wsgi:error] [pid 1043:tid 1147] [remote 49.228.84.26:9457] django.setup(set_prefix=False) [Wed Sep 11 06:36:45.998095 2024] [wsgi:error] [pid 1043:tid 1147] [remote 49.228.84.26:9457] File "/home/newsroom.dinsordesign.com/venv/lib64/python3.9/site-packages/django/init.py", line 24, in setup [Wed Sep 11 06:36:45.998103 2024] [wsgi:error] [pid 1043:tid 1147] [remote 49.228.84.26:9457] apps.populate(settings.INSTALLED_APPS) [Wed Sep 11 06:36:45.998114 2024] [wsgi:error] [pid 1043:tid 1147] [remote 49.228.84.26:9457] File "/home/newsroom.dinsordesign.com/venv/lib64/python3.9/site-packages/django/apps/registry.py", line 83, in populate [Wed Sep 11 06:36:45.998123 2024] [wsgi:error] [pid 1043:tid 1147] [remote 49.228.84.26:9457] raise RuntimeError("populate() isn't reentrant") i need some help what happend on my project i work on django i want to know what happend and how to fix it -
Django transaction is splitted, even if I use transaction.atomic()
with transaction.atomic(): A.objects.filter( a=a, b=b, c=c, d__range=[start_date, end_date], ).delete() A.objects.bulk_create( [ A( a=a, b=b, c=c, d=d, e=e, f=f, g=g, ) for obj in objs ] ) Query is like BEGIN BEGIN DELETE FROM ... COMMIT BEGIN INSERT INTO ... COMMIT What I want to do BEGIN DELETE FROM ... INSERT INTO COMMIT -
Django DRF error DLL Load Failed while importing _rust in Python 3.11.3 venv in Windows Server 2022 with cryptography-43.0.1-cp39-abi3-win_amd64.whl
My code is working in local environment of windows10 with venv on Python 3.10.11. However, on deploying in Windows Server 2022 with Apache2 webserver with venv on Python 3.11.3 getting following error. I have trying upgrading, installing binary. Till now issue is not resolved. Can anyone help in getting the issue resolved? from cryptography.hazmat.primitives.asymmetric import padding\r File "C:\\cbsesb\\cbsenv\\Lib\\site-packages\\cryptography\\hazmat\\primitives\\asymmetric\\padding.py", line 9, in <module>\r from cryptography.hazmat.primitives import hashes\r File "C:\\cbsesb\\cbsenv\\Lib\\site-packages\\cryptography\\hazmat\\primitives\\hashes.py", line 9, in <module>\r from cryptography.hazmat.bindings._rust import openssl as rust_openssl\r ImportError: DLL load failed while importing _rust: The specified module could not be found.\r Package Version asgiref 3.7.1 certifi 2023.7.22 cffi 1.17.1 charset-normalizer 3.3.2 cryptography 43.0.1 cx-Oracle 8.3.0 defusedxml 0.7.1 dicttoxml 1.7.16 Django 4.2.1 djangorestframework 3.14.0 djangorestframework-xml 2.0.0 idna 3.6 ldap3 2.9.1 lxml 4.9.3 mod-wsgi 4.9.4 pip 24.2 psycopg2 2.9.6 pyasn1 0.6.0 pycparser 2.22 pycryptodome 3.18.0 pyOpenSSL 24.2.1 pytz 2023.3 requests 2.31.0 setuptools 74.1.2 signxml 3.2.1 soupsieve 2.5 sqlparse 0.4.4 typing_extensions 4.6.1 tzdata 2023.3 urllib3 2.2.0 xmltodict 0.12.0 Tried to update the setup tools but did not worked python -m pip install --upgrade pip setuptools Tried to downgrade the Python to 3.10 but did not worked. installing Rust doesn't work. Tried installing binary for cryptography but did not worked. python -m pip … -
Django Microsoft SSO Integration State Mismatch (Django + Azure App Service)
I’m integrating Microsoft SSO into my Django app, and I’m encountering a "State Mismatch" error during the login process. This error occurs when the state parameter, which is used to prevent cross-site request forgery (CSRF) attacks, doesn’t match the expected value. What’s Happening: During the login process, my Django app generates a state parameter and stores it in the user’s session. When the user is redirected back to my app from Microsoft after authentication, the state parameter returned by Microsoft should match the one stored in the session. However, in my case, the two values don’t match, resulting in a State Mismatch Error. ERROR:django.security.SSOLogin: State mismatch during Microsoft SSO login. Expected state: XXXXXXXXXXXXXXXXXXXXXXXXXX Returned state: YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY Session ID: ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ Expected state: The state value generated by my app and stored in the session. Returned state: The state value returned by Microsoft after the user completes authentication. Session ID: The session key for the user during the login attempt. Django & Azure Configuration: Django version: 5.0.6 Python version: 3.12 SSO Integration Package: django-microsoft-sso Cache backend: LocMemCache (planning to switch to Redis) Azure App Service: Hosted with App Service Plan for deployment. Time Zone: Central Time (US & Canada) on local development … -
Error: 'Did you remember to import the module containing this task?'
I have this project https://github.com/LucasLeone/LaPanaSystem. I created a task for check the sales for change the state but doesn't work. The error: lapanasystem_local_celeryworker | [2024-09-10 23:47:20,238: ERROR/SpawnProcess-8] Received unregistered task of type 'check_sales_for_delivery'. lapanasystem_local_celeryworker | The message has been ignored and discarded. lapanasystem_local_celeryworker | lapanasystem_local_celeryworker | Did you remember to import the module containing this task? lapanasystem_local_celeryworker | Or maybe you're using relative imports? lapanasystem_local_celeryworker | lapanasystem_local_celeryworker | Please see lapanasystem_local_celeryworker | https://docs.celeryq.dev/en/latest/internals/protocol.html lapanasystem_local_celeryworker | for more information. lapanasystem_local_celeryworker | lapanasystem_local_celeryworker | The full contents of the message body was: lapanasystem_local_celeryworker | b'[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (77b) lapanasystem_local_celeryworker | lapanasystem_local_celeryworker | The full contents of the message headers: lapanasystem_local_celeryworker | {'lang': 'py', 'task': 'check_sales_for_delivery', 'id': '5cdd77f4-6b48-4274-8edb-0926ac3419e0', 'shadow': None, 'eta': None, 'expires': None, 'group': None, 'group_index': None, 'retries': 0, 'timelimit': [None, None], 'root_id': '5cdd77f4-6b48-4274-8edb-0926ac3419e0', 'parent_id': None, 'argsrepr': '()', 'kwargsrepr': '{}', 'origin': 'gen18@ace8c29fe6f1', 'ignore_result': False, 'replaced_task_nesting': 0, 'stamped_headers': None, 'stamps': {}} lapanasystem_local_celeryworker | lapanasystem_local_celeryworker | The delivery info for this task is: lapanasystem_local_celeryworker | {'exchange': '', 'routing_key': 'celery'} lapanasystem_local_celeryworker | Traceback (most recent call last): lapanasystem_local_celeryworker | File "/usr/local/lib/python3.12/site-packages/celery/worker/consumer/consumer.py", line 659, in on_task_received lapanasystem_local_celeryworker | strategy = strategies[type_] lapanasystem_local_celeryworker | ~~~~~~~~~~^^^^^^^ lapanasystem_local_celeryworker | KeyError: 'check_sales_for_delivery' I … -
How to set output dir dynamically to django app in TypeScript?
I have this webpack.config.js right now: const path = require('path'); const glob = require('glob'); const { log } = require('console'); const apps = ['transactions']; // List of apps with TypeScript files const getEntryObject = () => { const entries = {}; apps.forEach((app) => { const tsPath = path.join(__dirname, `dinotax/${app}/static/${app}/src/ts/**/*.ts`); glob.sync(tsPath).forEach((curPath) => { const name = path.basename(curPath, ".ts"); entries[name] = curPath; }); }) return entries; }; module.exports = { entry: getEntryObject(), output: { filename: '[name].js', // Output filename based on entry key path: path.resolve(__dirname, 'static'), }, resolve: { extensions: ['.ts'], }, module: { rules: [ { test: /\.css$/i, use: [ 'style-loader', 'css-loader' ] }, { test: /\.(ts|tsx)$/, exclude: [/node_modules/, /\.d\.ts$/], use: 'ts-loader', }, { test: /\.d\.ts$/, // Ensure .d.ts files are ignored use: 'ignore-loader', } ] }, }; The entry points would lock like this: --------------------- { fileTree: 'C:/repos/App/app/transactions/static/transactions/src/ts/fileTree/fileTree.ts', generalHelper: 'C:/repos/App/app/transactions/static/transactions/src/ts/helper/generalHelper.ts', matching: 'C:/repos/Dinotax/dinotax/transactions/static/transactions/src/ts/matching/matching.ts', overview: 'C:/repos/App/app/transactions/static/transactions/src/ts/overview/overview.ts', 'globals.d': 'C:/repos/App/app/transactions/static/transactions/src/ts/types/globals.d.ts', 'index.d': 'C:/repos/App/app/transactions/static/transactions/src/ts/types/index.d.ts' } --------------------- Which is what I want. The files are compiled, but now I struggle to set the output the same way I collect the files. I.e. files should be stored in the corresponding apps instead of the root static folder. An example would be: 'C:/repos/App/app/transactions/static/transactions/src/js/overview.d.js'. The Node Modules and webpack.config / … -
Django collecstatic requires STATIC_ROOT but setting STATIC_ROOT blocks upload to S3
So I use S3 static storage in combination with Django to serve static files for a Zappa deploy. This all worked quite well for a long time until I recently upgraded to a new Django version. Python 3.12.3 Django 5.1.1 It used to be, I could use: python manage.py collectstatic To push my static files over to my S3 bucket. But, currently, that fails with this error: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. However, If I set a STATIC_ROOT, then instead of pushing to S3, it collects the static files locally. You have requested to collect static files at the destination location as specified in your settings: /-local storage-/static This is my settings.py: STATIC_URL = '/static/' # STATIC_ROOT = os.path.join(BASE_DIR, "static") STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, "static") ] YOUR_S3_BUCKET = "static-bucket" STATICFILES_STORAGE = "django_s3_storage.storage.StaticS3Storage" AWS_S3_BUCKET_NAME_STATIC = YOUR_S3_BUCKET # These next two lines will serve the static files directly # from the s3 bucket AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % YOUR_S3_BUCKET STATIC_URL = "https://%s/" % AWS_S3_CUSTOM_DOMAIN The credentials and all are also in settings.py. It seems I a missing something, I need STATIC_ROOT to run collectstatic, but having STATIC_ROOT makes static collection … -
Electron Forge App: Issues with Executable Fiel Location in Release Build
I have an Electron Forge application designed to launch a Django server (on Windows). The Django server is compiled into an executable file using PyInstaller. The Electron Forge application invokes this executable file via the spawn command. When I build the Electron Forge application using npm run make, the application functions as expected. However, when using npm run release (which generates a setup file), the executable file cannot be located. Additionally, it does not exist in the resource folder. I get the error when starting the server: Error: spawn C:\Users\****\AppData\Local\Programs\****\resources\django-server\server.exe ENOENT My forge.config.ts file: Const config: ForgeConfig = { packagerConfig: { asar:true, icon "./src/assets/Logo/icon" extraResources: ['./django-server/server.exe'] } makers: [ new MakerSquirrel({noMsi: false}), new MakerZIP({}) ], .... The server.exe file is started inside the index.ts file by using spawn: exePath = path.join(process.resourcesPath, 'django-server', 'server.exe'); const child = spawn(exePath, []); Why is the server.exe file not being copied to the resource folder when running npm run release ?