Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why my response payload not getting parsed properly in django restframework?
I have below code: class MergeCompanyDetails(APIView): @staticmethod def get(_, id=None): api_log(msg="Processing GET request in MergeAccounts...") comp__id_client = Basic(base_url=settings.BASE_URL, token=settings.TOKEN, key=settings.KEY) try: organization_data = comp__id_client.account.info.retrieve(id=id, expand=CompanyInfo.XYZ) print('[organization_data1] :::', organization_data) except Exception as e: api_log( msg=f"Error retrieving organizations details: {str(e)} - Status Code: {status.HTTP_500_INTERNAL_SERVER_ERROR}: {traceback.format_exc()}") return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) # Create the payload dynamically from organization_data formatted_addresses = [ { "type": addr.type, "street_1": addr.street_1, "street_2": addr.street_2, "city": addr.city, "state": addr.state, "country_subdivision": addr.country_subdivision, "country": addr.country, "zip_code": addr.zip_code, "created_at": addr.created_at, "modified_at": addr.modified_at, } for addr in organization_data.addresses ] phone_types = [ { "number": phone.number, "type": phone.type, "created_at": phone.created_at, "modified_at": phone.modified_at, } for phone in organization_data.phone_numbers ] formatted_data = [] for org_tup in organization_data: organization = dict(org_tup[0]) print("@@@@@@@@@@@@@@@@@@@@@@@@@@", organization) formatted_entry = { "id": organization.get("id"), "remote": organization.get("remote"), "addresses": formatted_addresses, "phone_numbers": phone_types, } formatted_data.append(formatted_entry) api_log(msg=f"FORMATTED DATA: {formatted_data} - Status Code: {status.HTTP_200_OK}: {traceback.format_exc()}") return Response(formatted_data, status=status.HTTP_200_OK) when I simply print the organization_data, I get below output in the IDE console id='a5945ed8-932d-4c9d-9090-e8a50c58fbb6' remote_id='3f03913f-d173-4aa9-a7d8-cf8fc0525fa4' addresses=[Address(type=None, street_1='23 Main Street', street_2='Central City', city='Marinevill e', state='', country_subdivision='', country=None, zip_code='12345', created_at=datetime.datetime(2024, 1, 16, 6, 44, 57, 937035, tzinfo=datetime.timezone.utc), modified_at=datetime.datetime(2024, 1, 16, 6, 44, 57, 937052, tzinfo=date time.timezone.utc))] phone_numbers=[AccountingPhoneNumber(number='1234 5678', type='OFFICE', created_at=datetime.datetime(2024, 1, 16, 6, 44, 57, 965582, tzinfo=datetime.timezone.utc), modified_at=datetime.datetime(2024, 1, 16, 6, 44, 57, … -
celery dont do anything after recived a task from rabbitmq
iam running a simpel task to send email to user after ordering somthing in my django app i am using RabbitMQ as broker and i am running it on docker using : docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:management and running celery with celery -A myshop worker -l info i have this in my celery.py beside my setting.py file in main django app : import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings') app = Celery('myshop') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() and in the init.py file of the main django app : from .celery import app as celery_app __all__ = ['celery_app'] and this is the task in one of my django app from celery import shared_task from django.core.mail import send_mail from .models import Order @shared_task def order_created(order_id): """ Task to send an e-mail notification when an order is successfully created. """ order = Order.objects.get(id=order_id) subject = f'Order nr. {order.id}' message = f'Dear {order.first_name},\n\n' \ f'You have successfully placed an order.' \ f'Your order ID is {order.id}.' mail_sent = send_mail(subject, message, 'email@gmail.com', [order.email]) return mail_sent celery getting the order like this : [2024-01-25 16:12:51,674: INFO/MainProcess] Task orders.task.order_created[679c4592-e5e2-42f4-9f15-b07f9492fce3] received [2024-01-25 … -
Django x Postgres Migrate and Migration error
I get this error anytime i run makemigrations: /home/azeez/bendownselect/venv/lib/python3.12/site-packages/django/core/management/commands/makemigrations.py:160: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "postgres" to address: Temporary failure in name resolution and i get this error if i run migrate: django.db.utils.OperationalError: could not translate host name "postgres" to address: Temporary failure in name resolution this is my db config: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': env("POSTGRES_DB"), 'USER': env("POSTGRES_USER"), 'PASSWORD': env("POSTGRES_PASSWORD"), 'HOST': env("POSTGRES_HOST"), 'PORT': env("POSTGRES_PORT"), } } Thank you! -
Python Rest Api GroupDocs
I am trying to convert ppt file into pdf and then save it into a file. I am able to upload to the cloud of GroupDocs, Convert to PDF, but last step, download the file doesnt work. Some errors that gives me are my folder doesnt exist and I cant find PDF downloaded in any place. def generate_and_save_pptx(self): # Ruta del PPTX a modificar pptx_template_path = 'panel/templates/originals/Prueba.pptx' presentation = Presentation(pptx_template_path) # modifico ppt self.modify_presentation(presentation) # Ruta PDF final pdf_filename = f'{self.client.name} - {self.type_submission.name}_tutorial.pdf' pptx_filename = f'{self.client.name} - {self.type_submission.name}_tutorial.pptx' pdf_path = submission_directory_path(self, pdf_filename) my_storage = "FilesToConvert" pdf_cloud_path = f'FilesToConvert/{pdf_filename}' # Usar / en lugar de \ # Crear un archivo temporal para guardar el PPTX with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as temp_pptx: temp_pptx_path = temp_pptx.name presentation.save(temp_pptx_path) try: # Crea una instancia de la api file_api = FileApi(Configuration(app_sid, app_key)) # Subir el archivo upload_request = UploadFileRequest(pptx_filename, temp_pptx_path, my_storage) file_api.upload_file(upload_request) except ApiException as e: print(f"Error durante la carga del archivo PPTX: {e}") try: # Crear una instancia de la API convert_api = ConvertApi.from_keys(app_sid, app_key) # Configurar las opciones de conversión convert_settings = ConvertSettings() convert_settings.file_path = pptx_filename # El nombre del archivo subido convert_settings.format = "pdf" convert_settings.output_path = my_storage # Crear la solicitud de conversión del … -
dynamically changing text on a page using CKEditor 5 in django
please tell me, is there a ready-made solution for Ckeditor - 5 to change the contents of the page without going to the admin panel, as well as without refreshing the page? example: in general, you can do this yourself using forms and ajax, for example, but why invent a bicycle if you already have one? -
How to display card picture to the right side of the text?
I've started writing my first website project using django (recipe storage website). I've imported a template for the whole project and it came with its own stylesheet and other bits and bobs. Now, I am writing a page where I want to display all the recipes that are in the database. For that, I also borrowed a recipe display card template (it came with its own HTML and CSS). So, I looked up how to merge them and for the most part it works and displays properly. However, whatever I do, for the life of me I can't seem to make the image of the card to display to the right of the text (within the card), even though I've pasted my stylesheet and the cards style and HTML into jsfiddle.net and it displays perfectly. It only ever displays below the text. I assume it's not a conflict with my existing stylesheet, because none of the class names in the imported card stylesheet are the same as ones in my existing one, but I've been banging my head at this problem for like 8 hours now, and I can't seem to get it to work. I feel like I am … -
How to convert calculated properties (that involve calling other methods) into Django generated fields?
Let's say I have this following model: class Product(models.Model): price = models.DecimalField( max_digits=19, decimal_places=4, validators=[MinValueValidator(0)], blank=False, null=False, ) expiry_date = models.DateTimeField( blank=True, null=True, ) @property def price_in_cents(self): return round(self.price * 100) @property def has_expired(self): if self.expiry_date: return date.today() > self.expiry_date.date() else: return False So two fields, and two other properties that rely on these two fields to generate an output. I'm trying to convert these fields into generated fields (for Django 5). My first understanding was simply just putting in the property function in the expression, so something like this: class Product(models.Model): price = models.DecimalField( max_digits=19, decimal_places=4, validators=[MinValueValidator(0)], blank=False, null=False, ) price_in_cents = models.GeneratedField( expression=round(F("price") * 100), output_field=models.BigIntegerField(), db_persist=True, ) expiry_date = models.DateTimeField( blank=True, null=True, ) @property def has_expired(self): if self.expiry_date: return date.today() > self.expiry_date.date() else: return False Unfortunately, this does not seem to work, and I get the following error: TypeError: type CombinedExpression doesn't define round method Going by this, I assume I won't be able to simply convert the second property either. So how would this actually work? Is there a resource to help me convert these Python functions (properties) into valid expressions? -
Apache mod_wsgi macOS Error: Cannot load mod_wsgi.so - Library not loaded: @rpath/libpython3.9.dylib
I'm setting up a Django project with Apache and mod_wsgi on macOS using Homebrew. When I restart the Apache server, I encounter the following error: httpd: Syntax error on line 67 of /usr/local/etc/httpd/httpd.conf: Cannot load /usr/local/lib/httpd/modules/mod_wsgi.so into server: dlopen(/usr/local/lib/httpd/modules/mod_wsgi.so, 0x000A): Library not loaded: @rpath/libpython3.9.dylib Referenced from: /usr/local/Cellar/httpd/2.4.58/lib/httpd/modules/mod_wsgi.so Reason: no LC_RPATH's found context: Installed Apache using Homebrew. Installed mod_wsgi using pip. Apache configuration file (httpd.conf) includes the following block: <VirtualHost *:8080> ServerName webmaster@localhost DocumentRoot /var/www/html Alias /static /Users/abbasahmed/Desktop/AWD/topic9/bioweb/static <Directory /Users/abbasahmed/Desktop/AWD/topic9/bioweb/static> Require all granted </Directory> <Directory /Users/abbasahmed/Desktop/AWD/topic9/bioweb/bioweb> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess bioweb python-path=/Users/abbasahmed/Desktop/AWD/topic9/bioweb python-home=/Users/abbasahmed/Desktop/AWD/topic9/envs/bioweb_install WSGIProcessGroup bioweb WSGIScriptAlias / /Users/abbasahmed/Desktop/AWD/topic9/bioweb/bioweb/wsgi.py </VirtualHost> I also include this with the other module loading code in the config file LoadModule wsgi_module /usr/local/lib/httpd/modules/mod_wsgi.so I'm facing an issue with Apache and mod_wsgi on macOS. The error suggests a problem with the library path (@rpath/libpython3.9.dylib). How can I resolve this issue and successfully load mod_wsgi.so into the Apache server? I uninstalled and installed mod_wsgi with the correct python version but I still get an error -
Setting up pytest django database
I need to run this SQL after the test database is created but before creating any tables: `CREATE EXTENSION pg_trgm; CREATE EXTENSION btree_gin; I know that I can somehow use django_db_setup fixture to do this but I can't figure out how. I use addopts = --no-migrations in my pytest.ini file so this can't be done using migrations It should be something like this: @pytest.fixture(scope='session') def django_db_setup(): # Some code to create database with connection.cursor() as cursor: cursor.execute('CREATE EXTENSION IF NOT EXISTS pg_trgm;') cursor.execute('CREATE EXTENSION IF NOT EXISTS btree_gin;') # Code for creating tables -
AJAX call to Django View returns None
I trying to get data which I send with AJAX base.html <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <script> function getAjaxResponse() { console.log('myAjax'); $.getJSON('/ajax', { get_param: 'data' }, function(data) { $.each(data, function(key, val) { console.log(key); console.log(val); }); }); } $(function(){ $("input[name='barcode']").change(function() { var barcode = document.getElementById("id_barcode").value; $.ajax({ type:'GET', url:`ajax/?variable=${barcode}`, headers: {'X-CSRFToken': '{{ csrf_token }}'}, success: function(response){ console.log('success'); console.log(barcode); setTimeout(getAjaxResponse, 3000); }, error: function (response){ console.log('error'); } }); }); }); </script> urls.py path('ajax/', views.ajaxBarcode, name='ajaxBarcode'), views.py def ajaxBarcode(request): barcode = request.GET.get('variable') dict = {} if len(str(barcode)): dict['hint1'] = str(barcode) return JsonResponse(dict) When I retrieve data in browser I always had hint1 and None. But when I type in address line /ajax/?variable=115 I have response {"hint1": "115"} -
How to create a form that updates multiple field for multiple user simultaneously in Django?
I want to create a form that able to take multiple respond and update the database for multiple instances. Here is my case: I have 2 models, Members and Cash class Members(models.Model): nim = models.IntegerField(default=0) name = models.CharField(max_length=40) position = models.CharField( max_length=30, choices=POSITION_OPTION, ) year = models.IntegerField() program = models.CharField(max_length=30) potrait = models.CharField(max_length=100, default='NO PHOTO') class Cash(models.Model): name = models.ForeignKey(Members, on_delete=models.CASCADE) jan = models.BooleanField(default=False) feb = models.BooleanField(default=False) mar = models.BooleanField(default=False) apr = models.BooleanField(default=False) may = models.BooleanField(default=False) jun = models.BooleanField(default=False) jul = models.BooleanField(default=False) aug = models.BooleanField(default=False) sep = models.BooleanField(default=False) The logic behind this model is, each Member has their record of Cash. So my end goal is to sum the number of True in each Member and determine how much cash they have deposited to the organization. Back to the topic, I want to create a form page that is formed like tables, NIM January February So on... 010456 [ ] (checkbox) [ ] (checkbox) So on... ----------- --------------------------- --------------------------- ------------------ 010457 [ ] (checkbox) [ ] (checkbox) So on... <button>UPDATE RECORD</button> But I'm stuck at figuring out how to connect this multiple form to multiple user at once. The alternative way I can achieve my end goal is to create … -
Test (selenium) Google Oauth login on my Django website
On our login screen we have a Google login. But when I try to test it with Selenium I get an error at Google saying: "device_id and device_name are required for private IP: http://..../accounts/google/login/callback/" Error 400: invalid_request. Now I have (I think) 2 options: Make it so the request is valid. Check the request we send to Google to see if it is valid Oauth and fake a response that back. But I have no idea how to do them and which one is better then the other one. The request we send to google has this payload: "client_id": "redirect_uri": "scope": "response_type": "state": "access_type": <!--begin::Google link--> <a href="{% provider_login_url "google" %}" class="btn btn-flex flex-center btn-light btn-lg w-100 mb-5"> <img alt="Logo" width="28" height="28" src="{% manifest "media/svg/brand-logos/google-icon.svg" %}" class="h-20px me-3" /> {% trans "Continue with Google" %} </a> <!--end::Google link--> When I tried clicking in the Selenium browser on the google I Expected for it to show the normal google login. Instead of the normal google login I got an error. -
Page not found (404) No Profile matches the given query. using django multi tenants
I am encountering a 404 error with the message "No Profile matches the given query" when trying to access the crm_details view with profile IDs higher than 4 in a multi-tenancy Django application views.py def crm_details(request, profile_id): if request.user.is_authenticated: tenant = Tenant.objects.get(schema_name=request.tenant) # Fetch the current tenant profile = get_object_or_404(Profile, id=profile_id, tenant=tenant) # Filter by tenant crm_instance = crm.objects.filter(person_detail=profile, tenant=tenant).first() # Filter by tenant properties = AddProperty.objects.filter(tenant=tenant) if request.method == 'POST': form = crmForm(request.POST, instance=crm_instance) if form.is_valid(): crm_entry = form.save(commit=False) crm_entry.person_detail = profile crm_entry.save() else: form = crmForm(instance=crm_instance) context = { 'profile': profile, 'crm_form': form, 'properties': properties } return render(request, 'crm_details.html', context) return redirect("blog:user_login") def create_profile(request): if request.user.is_authenticated: tenant = Tenant.objects.get(schema_name=request.tenant) # Fetch the current tenant if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.tenant = tenant # Associate the profile with the current tenant profile.save() return redirect('blog:profile_list') else: form = ProfileForm() return render(request, 'create_profile.html', {'form': form}) return redirect("blog:user_login") def add_property(request): if request.user.is_authenticated: tenant = Tenant.objects.get(schema_name=request.tenant) # Fetch the current tenant if request.method == 'POST': form = AddPropertyForm(request.POST, request.FILES) if form.is_valid(): property_instance = form.save(commit=False) property_instance.tenant = tenant # Associate the property with the current tenant property_instance.created_by = request.user property_instance.save() return redirect('blog:property_list') else: form = AddPropertyForm() else: … -
how to make a Clickmap on a Django application?
`Hello! I'm building an application with django and I need to make a clickmap/heatmap to get some statistics from my site. My problem: almost all the forms are out of date and I don't want to use Google Analytics or anything like that. I need a visual map that shows me where users are clicking, the most accessed pages, etc. Things i tried: https://django-analytical.readthedocs.io/en/latest/ clickmap.js https://learn.microsoft.com/en-us/clarity/setup-and-installation/clarity-setup` -
I cant add Products to admin
Im having some errors updating products in my Django adminthe error that shows up whenever I try to add a new product it keeps telling me to return to my django root file and make some changes{Error that comes up} I was expecting a successful operation that says product added successfully OperationalError at /admin/products/product/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/products/product/add/ Django Version: 2.1 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Python\Python37\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 296 Python Executable: C:\Python\Python37\python.exe Python Version: 3.7.4 Python Path: ['C:\Users\Admin\Desktop\Afresh', 'C:\Python\Python37\python37.zip', 'C:\Python\Python37\DLLs', 'C:\Python\Python37\lib', 'C:\Python\Python37', 'C:\Python\Python37\lib\site-packages'] Server time: Thu, 25 Jan 2024 11:31:08 +0000 -
Django-Python easy way to convert PPTX to PDF?
I have tried several libraries for convert a PPTX file to PDF and all of them gives me error. For example I am trying to use an API of SDK python of GroupDocs, this is my method: def generate_and_save_pptx(self): pptx_template_path = ‘panel/templates/originals/Prueba.pptx pdf_filename = f’{self.client.name} - {self.type_submission.name}_tutorial.pdf’ pdf_path = submission_directory_path(self,pdf_filename) api_instance = groupdocs_conversion_cloud.ConvertApi.from_keys(app_sid, app_key) convert_request = groupdocs_conversion_cloud.ConvertDocumentDirectRequest( "pdf", pptx_template_path, # Reemplaza con la ruta correcta a tu archivo None, None, None ) try: response = api_instance.convert_document_direct(convert_request) with open(pdf_path, "wb") as pdf_file: pdf_file.write(response) Debugging it looks like I cant even enter into response. On the other hand it says folder doesnt exist but it exists, I save other files there without problem. Any other libraries I have tried always have similar problemas, not enter into the response, save data corrupted, etc. I just would like to find and easy and free way to convert pptx files to pdf -
logout in drf api browsable it shows HTTP ERROR 405
I perform logout and login operations in Djnago Rest Framework. I logout using drf api browsable it shows HTTP ERROR 405 my version is Django==5.0.1 when i decrease version Django==3.2.10 it works perfect Is there any solution in Django==5.0.1 to resolve this issue ? -
Fire & Forget Asyncio
I've been scouring the web to an answer to this question but I can't seem to find an actual answer or maybe i'm just missing it. I'm trying to fire off a post request to start another microservice and I don't care what response comes back as that goes to a different part of my architecture Once the request is sent I want to essentially continue the code a return this random json to where the function is called. For some reason whenever I use asyncio.run() it starts the send_requests() function but waits for it to respond before continuing. Which is how async works i this case I think. But i'm unsure how to continue and exit the function before waiting for a response Here's the pseudo code Class DummyClass: def do_something(): "doing something...." asyncio.run(send_requests) return "random string" async def send_request(): try: requests.post("send to url") except: raise Issue I can use a decorator def fire_and_forget(f): @wraps(f) def wrapped(*args, **kwargs): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) if callable(f): return loop.run_in_executor(None, f, *args, **kwargs) else: raise TypeError("Task must be a callable") return wrapped which works fine but just wondering if we can do it without the decorator! I think I might be slightly misunderstanding … -
Django use F() to the jsonField and there is json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
this is the code class Helo(models.Model): id = models.IntegerField(primary_key=True) aa = models.JSONField(null=True) bb = models.JSONField(null=True) one example data is this: id aa bb 1 {"p1":11 "p2": 22} {"p1": 33, "p2": 44} and i run this code test=Helo.filter(aa__p1__gte = F('bb__p1')) test.count() get these error message json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) i also tried the test=Helo.filter(aa__p1__gte = F('bb')) test.count() and there is no error, i wonder why i cant use the F('bb__p1') -
Django DATE and DATETIME settings have no effect since USE_L10N was deprecated
Since 5.0 USE_L10N settings was DEPRECATED and is always True. Now settings like DATE_FORMAT, DATETIME_FORMAT, DATE_FORMAT_INPUTS etc.. don't work because as per documentation: Note that the locale-dictated format has higher precedence and will be applied instead. But now locale-dictated formats are always enabled. A fix I've found is to copy the formats.py file you want to in your app's directory. The path should look like <your_project>/<your_app>/formats/ro/formats.py then in settings.py you can set: LANGUAGE_CODE = 'ro-RO' FORMAT_MODULE_PATH = ['yourapp.formats',] But why have those settings anymore? Is there any way in which you can still use those settings? -
How to add an accordion in djnago admin in the change_list.html template?
I want to change the default table in the django admin, which is displayed in the template change_list.html. While retaining all the functionality that django provides. The idea is to make the table in the form of an accordion, where there will be a button "Collapse" and "Expand". In the case of clicking the button "Expand" will expand the column with the associated record and all its data Can you tell me how to implement such functionality, I will be glad to receive any suggestions? In simpler words, how to add the action "view_data" and when you click "Open" button the accordion will open and show all the data related to the record table -
how to solve CORS error in react and django
i am trying to creat log in app using Django and react . my js : const client = axios.create({ baseURL: "http://127.0.0.1:8000"}); //my submitRegistration function function submitRegistration(e) { e.preventDefault(); client.post( //every time I got cors error here// "/api/register", { email: email, username: username, password: password } ).then(function(res) { client.post( "/api/login", { email: email, password: password } ).then(function(res) { setCurrentUser(true); }); });} django cors setup: CORS_ALLOWED_ORIGINS = [ 'http://localhost', 'http://127.0.0.1', 'http://0.0.0.0', ] CORS_ALLOW_CREDENTIALS = True I dont know why I got cors error here.any suggestion please! -
What is this little note below DateField that is displayed in Django Admin?
Hi I have defined a CD Model in my models.py file in my app and linked it to the admin page. However, I noticed this little note below the Date field. 'You are 8 hours ahead of server time'. What does it mean? I tried finding information about it but still couldn't get a good understanding of it. -
python dict weird assign of a key value (multiple keys are created)
I run the following code (django framework, but it doesn't seem relevant) def asignador(self) -> dict: try: a_asignar = deepcopy(list(self.materias)) dict_mezclado = deepcopy(Biotcher.mezclador(self.dict_de_asignaciones)) divisiones_mezcladas = deepcopy(Biotcher.mezclador(self.divisiones_habilitadas_por_materia)) shuffle(a_asignar) nueva_grilla = deepcopy(self.grillas) for materia_a_asignar in a_asignar: materia_a_asignar = a_asignar[0] division_asignada = divisiones_mezcladas[materia_a_asignar.materia.pk][-1] ##### horas_div = materia_a_asignar.materia.horas_por_semana for _ in range(horas_div): dia, hora = dict_mezclado[division_asignada][-1] print(nueva_grilla[division_asignada]) nueva_grilla[division_asignada][dia][hora]['mat'] = materia_a_asignar.materia.nombre print(nueva_grilla[division_asignada]) dict_mezclado[division_asignada].pop(-1) divisiones_mezcladas[materia_a_asignar.materia.pk].pop(-1) return nueva_grilla except Exception: print('EXCEPCION') print(nueva_grilla) The first print I obtain {1: {1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 2: {1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 3: {1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 4: {1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 5: {1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}} and in the second one {1: {1: {'mat': 'Pol y Ciud.'}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 2: {1: {'mat': 'Pol y Ciud.'}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 3: {1: {'mat': 'Pol y Ciud.'}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 4: {1: {'mat': 'Pol y Ciud.'}, 2: {}, 3: {}, 4: {}, … -
I am tying to create .exe for my django I used python freeze_script.py build but I'm getting error
# freeze_script.py import os import sys from cx_Freeze import setup, Executable from django.core.management import call_command from django.core.wsgi import get_wsgi_application # Manually configure Django settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DVE.settings') # Replace 'your_project_name.settings' with your actual settings module application = get_wsgi_application() # Your Django project name (replace 'your_project_name' with your actual project name) project_name = 'DVE' base = None if sys.platform == "win32": base = "Win32GUI" executables = [ Executable("manage.py", base=base) ] # Call the 'migrate' command before freezing call_command("migrate") # Freeze the application build_options = { 'packages': ['DVE','TOOL', 'django', 'gunicorn'], 'includes': ['django.template.backends', 'django.templatetags.i18n'], } setup( name="TOOL", version="1.0", description="TOOL", options={"build_exe": build_options}, executables=executables ) Traceback (most recent call last): "C:\Users\AAMOLGHA\AppData\Local\Packages\PythonSoftwa reFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-p ackages\Python310\site-packages\cx_Freeze\initscripts_start up_.py", line 124, in run File module_init.run(name + "main_") File "C:\Users\AAMOLGHA\AppData\Local\Packages\PythonSoftwa reFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-p ackages\Python310\site-packages\cx_Freeze\initscripts\consol e.py", line 16, in run exec(code, module_main.dict_) File "manage.py", line 22, in <module> File "manage.py", line 18, in main File "C:\Users\AAMOLGHA\AppData\Local\Packages\PythonSoftwa reFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-p ackages\Python310\site-packages\django\core\management\ init_.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\AAMOLGHA\AppData\Local\Packages\PythonSoftwa reFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-p ackages\Python310\site-packages\django\core\management\ init_.py", line 424, in execute sys.stdout.write(self.main_help_text() + "\n") AttributeError: "NoneType' object has no attribute 'write' this is the error your text