Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Formatting not being applied to Django form in iOS Safari
This the html code which is producing a 'search bar' for the user to input text: <form id="searchForm" method="GET" action="{% url 'search_mountains' %}#search-and-grid"> {{ form.as_p }} </form> The formatting is declared in the associated CSS: #searchForm input[type="text"] { background-color: rgb(255, 255, 255); color: #303030; display: inline-block; border: #07A3B2 solid 1.75px; padding-left: 7px; font-size: 0.65em; border-radius: 8px; margin-left: 0px; cursor: pointer; opacity: 0.9; width: 150px; -webkit-appearance: none; -webkit-user-select: text; /* Chrome, Opera, Safari */ -moz-user-select: text; /* Firefox 2+ */ -ms-user-select: text; /* IE 10+ */ user-select: text; /* Standard syntax */ -moz-appearance: none; appearance: none; } Which produces the expected result: This formatting is being applied on desktop versions both locally and when deployed in AWS elastic beanstalk and works fine when working locally, even for iOS safari, however when accessing the deployed website in iOS safari the formatting is not being applied: This is only happening when loading the website in 'production' in iOS Safari, it works fine in Google Chrome for iOS for instance. I've tried changing the html syntax to a direct tag rather than a Django input but the same result persists. -
Problem with running a python code with NLTK on Render platform
I have my django project running on Render just fine, and i've been considering on implementing a chatbot using nltk. The problem occurs the moment the project itself is about to run. For some reason, it keeps trying to access stopwords multiple times and then saying that it is already updated. It keeps going without stopping whatsoever. [nltk_data] Downloading package stopwords to /opt/render/nltk_data... [nltk_data] Unzipping corpora/stopwords.zip. [nltk_data] Downloading package stopwords to /opt/render/nltk_data... [nltk_data] Package stopwords is already up-to-date! [nltk_data] Downloading package stopwords to /opt/render/nltk_data... [nltk_data] Package stopwords is already up-to-date! These are the messages that keeps repeating. [nltk_data] Downloading package stopwords to /opt/render/nltk_data... [nltk_data] Package stopwords is already up-to-date! [2024-04-02 16:53:45 -0400] [59] [CRITICAL] WORKER TIMEOUT (pid:60) [2024-04-02 16:53:45 -0400] [60] [INFO] Worker exiting (pid: 60) [2024-04-02 16:53:47 -0400] [59] [ERROR] Worker (pid:60) was sent SIGKILL! Perhaps out of memory? [2024-04-02 16:53:47 -0400] [68] [INFO] Booting worker with pid: 68 [nltk_data] Downloading package stopwords to /opt/render/nltk_data... [nltk_data] Package stopwords is already up-to-date! Ant this is what causes it to go in a loop again. import nltk import re import os import csv from nltk.stem.snowball import SnowballStemmer import random from nltk.classify import SklearnClassifier from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords … -
libgeos.py MemoryError on GeoDjango project
I'm developing a GeoDjango project on Rocky Linux 9 and deploying using Apache. The application ran fine before when I used the standard Postgres database engine: "ENGINE": "django.db.backends.postgresql", but as soon as I swap to the PostGIS backend engine: 'ENGINE': 'django.contrib.gis.db.backends.postgis', I get the following error: File "/home/centurion/centurion_web/.venv/lib/python3.12/site-packages/django/contrib/gis/db/backends/postgis/base.py", line 7, in from .adapter import PostGISAdapter File "/home/centurion/centurion_web/.venv/lib/python3.12/site-packages/django/contrib/gis/db/backends/postgis/adapter.py", line 5, in from django.contrib.gis.geos import GEOSGeometry File "/home/centurion/centurion_web/.venv/lib/python3.12/site-packages/django/contrib/gis/geos/init.py", line 5, in from .collections import ( # NOQA File "/home/centurion/centurion_web/.venv/lib/python3.12/site-packages/django/contrib/gis/geos/collections.py", line 5, in from django.contrib.gis.geos import prototypes as capi File "/home/centurion/centurion_web/.venv/lib/python3.12/site-packages/django/contrib/gis/geos/prototypes/init.py", line 7, in from django.contrib.gis.geos.prototypes.coordseq import ( # NOQA File "/home/centurion/centurion_web/.venv/lib/python3.12/site-packages/django/contrib/gis/geos/prototypes/coordseq.py", line 3, in from django.contrib.gis.geos.libgeos import CS_PTR, GEOM_PTR, GEOSFuncFactory File "/home/centurion/centurion_web/.venv/lib/python3.12/site-packages/django/contrib/gis/geos/libgeos.py", line 88, in notice_h = NOTICEFUNC(notice_h) ^^^^^^^^^^^^^^^^^^^^ MemoryError I hadn't even implemented any geospatial code in the application yet. I have a development server on windows that the application runs normally on with that engine using the runserver command. I've tried directly setting the GEOS_LIBRARY_PATH and GDAL_LIBRARY_PATH with no success. I downgraded from django 5.0 to 4.2 with no success. -
CORS headers not allowed in Django
I am developing an API in Django and using next js as the frontend. But each time I try to call the back end to the next js fronend I get on the console Access to XMLHttpRequest at 'http://127.0.0.1:8000/' from origin 'http://0.0.0.0:3000' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space `local` I also get this Login error: AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …} code : "ERR_NETWORK" I did the following I added to the first line of the middleware section 'corsheaders.middleware.CorsMiddleware', to my settings.py after install django cors headers Stopped and restarted the server I also ``` CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', 'http://127.0.0.1:3000', 'http://0.0.0.0:3000', ] and yet i still get the problem -
Tables-2 django features for the implementation of my project
I need help with the idea of implementing the project. Initially, the task was to create a custom desktop application for several people to work simultaneously with the database on the server (editing, filtering). The database consists of several main tables, the rows of these tables should be linked to pages with more detailed information (for example, links to products in an online store). There should be such a link for each line. I decided to use django with the django-tables2 module, but I can't figure out if it's possible to use it to implement everything I need? Or will I need something else? Before that, I tried the django-dynamic-datatb module, but could not find a solution that allows you to link each row of the table to a separate page. There is also no html code, so it was not possible to create a menu to navigate from one table to another. It's worth clarifying, I need to use sql express. -
Can I declare two ForeignKey to the same table in one Django ORM abstract model?
Can you tell me if I can declare two ForeignKey to the same table in the same abstract model? I can do: class TrackableDateModel(models.Model): """Abstract model to Track the creation/updated date for a model.""""" create_date = models.DateTimeField(auto_now_add=True, help_text="Creation time", verbose_name="Created", null=True, blank=True) create_user = models.ForeignKey(User, related_name="create_user", on_delete=models.CASCADE, help_text="Who created", verbose_name="Author", null=True, blank=True) update_date = models.DateTimeField(auto_now=True, help_text="Time of change", verbose_name="Changed", null=True, blank=True) class Meta: abstract = True class A(TrackableDateModel): .... class B(TrackableDateModel): ..... But can't add to TrackableDateModel: update_user = models.ForeignKey(User, related_name="update_user", on_delete=models.CASCADE, help_text="Who modified", verbose_name="Author of change", null=True, blank=True) Because makemigrations swears. ERRORS: DjModule.A.create_user: (fields.E304) Reverse accessor 'User.create_user' for 'DjModule.A.create_user' clashes with reverse accessor for DjModule.B.create_user'. HINT: Add or change a related_name argument to the definition for 'DjModule.A.Export4Payment.create_user' or 'DjModule.B.create_user'. and crashes... -
How to solve "Import "rest_framework.views" not resolved" error after successfully installing the djangorestframework
I have just installed the Djangorestframework in my Django project for the first time. Before installing all the required dependencies (djangorestframework being one of them), I created a virtual environment (venv) were my project can run. Also I have created a virtual server where my project runs using Vagrant (ubuntu/bionic64). I installed Django 3.2.10, django-rest-framework 3.12.4 and python 3.6.9 So after all this configurations when i try to import some classes from django-rest-framework and registered the "rest_framework" in INSTALLED_APPS in the settings.py, the imported commands are underlined using yellow lines. For example: from rest_framework.views import APIview, the phrase "rest_framework" is underlined in yellow, what could be the problem? I tried several solutions but that didn't I re-installed the djangorestframe work package and tried to use it Since sometimes your IDE can cache some data making it difficult for your rest_framework to run, so I re- stared my IDE (Vs code) I also restarted my PC in case it had any problem. I changed my python interpreter to include the one with virtual environment but still did not work. I tried to check for typos and resolved but the problem still persisted. -
Best Practices for Form Rendering Fields in Django Forms
I'm looking to optimize the rendering of form fields in a Django ModelForm and ensure adherence to best practices. Currently, I've implemented a method as_custom_div within my ModelForm class to customize the rendering of form fields. Here's the method I've defined: def as_custom_div(self): output = '' for field in self: output += f'<div class="input-container">{field}</div>' return output In my template, I'm using this method to render the form fields: <form action=""> {{form.as_custom_div|safe}} <input type="submit" value="Submit"> </form> While this approach works, I'm curious if there's a more efficient or conventional way to achieve the same result. I want to ensure that I'm following best practices for rendering form fields in Django. Any insights or alternative approaches would be appreciated. Thank you!" -
Django reactions emoji
I tried to implement reactions on my django blog website the json request from the views are working properly but the ajax prevents normal form submission but doesn't update the ui and also doesn't update the reaction count I tried severally it's not working but the json is working and when click it's return the reaction clicked but doesn't update the ui -
redis.exceptions.ResponseError: WRONGTYPE Operation against a key holding the wrong kind of value
I am working on a stock market app. where i am pushing all the callback from order subscription to redis queue and then executing further action based on the order executed. for OrderQId in scriptSeries.OrderQId: if OrderQId is not None: mq = MessageQueue(OrderQId) mq.clearQueue() using a custom lass call MessageQueue where i have implemented all redis method. class MessageQueue(): def __init__(self, QueueId): self.QueueId = QueueId self.Redis = StrictRedis() # self.Redis = StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB, charset="utf-8", decode_responses=True) when clearing the queue by poping out element, it throws "redis.exceptions.ResponseError: WRONGTYPE Operation against a key holding the wrong kind of value" sharing the current situation of the keys and tried passing binary value with encoding utf as well without any luck. also tried with redis and stricredis the same code is working in my .ipynb code on the same system. also below code from redis.io works fine. res1 = r.lpush("bikes:repairs", "bike:1") print(res1) # >>> 1 res2 = r.lpush("bikes:repairs", "bike:2") print(res2) # >>> 2 res3 = r.rpop("bikes:repairs") print(res3) # >>> bike:1 res4 = r.rpop("bikes:repairs") print(res4) # >>> bike:2 Not sure what wrong i am doing. -
Django Window-function Lag empty after filter()
I have a Django app where I maintain music charts. Each chart contains episodes with positions. An entry in the episode consists of a position and a track. Now, I want to display an episode from the chart along with all positions, as well as the position of the track in the previous and next episodes. My models are structured as follows: class Episode(models.Model): chart = models.ForeignKey( "Chart", on_delete=models.CASCADE, related_name="episodes" ) pub_date = models.DateField() class Track(models.Model): artist = models.CharField() title = models.CharField() class Entry(models.Model): episode = models.ForeignKey( Episode, on_delete=models.CASCADE, related_name="entries" ) track = models.ForeignKey( Track, on_delete=models.CASCADE, null=True, related_name="entries" ) position = models.PositiveIntegerField() My queryset looks like this: window = { "partition_by": [F("track")], "order_by": [F("pub_date").asc()], } Entry.objects.filter(episode__chart=1).annotate( prev_position=Window(expression=Lag("position", 1), **window), next_position=Window(expression=Lead("position", 1), **window), ).filter(episode=3) When I remove the filter(episode=3) part, I see filled prev_position and next_position, but when I add that last filter, the Window functions are no longer populated. What am I missing? -
I keep getting many "ImportError: cannot import name" errors from files I've never touched and names I've never heard of
Working on a project for uni using Django and after fixing problems within programs I've created, I've started getting errors within files I've never touched. Most recent one is " ImportError: cannot import name 'Count' from partially initialized module 'django.db.models.aggregates' (most likely due to a circular import) (C:\Users\leond\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\db\models\aggregates.py)" But when I go into aggregates.py and delete the "import Count" line just to see if that does anything, it then gives the same error for 'BaseExpression' within "expressions.py". I just don't understand what's going on, and I know it's likely due to circular imports but I have no idea how to fix it. I simply tried running python3 manage.py runserver in the Terminal, and I expected it to work due to me thinking I fixed a previous issue, but then the console spits out this: Traceback (most recent call last): File "C:\Users\leond\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\management_init_.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\leond\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\leond\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django_init_.py", line 16, in setup from django.urls import set_script_prefix File "C:\Users\leond\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\urls_init_.py", line 1, in from .base import ( File "C:\Users\leond\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\urls\base.py", line 8, in from .exceptions import NoReverseMatch, Resolver404 File "C:\Users\leond\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\urls\exceptions.py", line 1, in from django.http import Http404 File "C:\Users\leond\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\http_init_.py", line 9, in from django.http.response import … -
is ther a good way to read dictionart in the list from a scrapping file so as to be read by views.py file
like this Split result: [{'index': 'PS0191007-001', 'sex': 'M', 'name': 'FNAME LNAME', 'subjects': 'Kisw - B, Eng - B, Maarifa - B, Hisabati - A, Science - B, Grade - B'}] This came from the scrapping file " if occurrences: results = [] for occurrence in occurrences: parent_tr = occurrence.find_parent('tr') if parent_tr: results.append(parent_tr.text.strip()) parsed_results = [] for result in results: matokeo = re.split(r'\s{2,}', result) index = matokeo[0] sex = matokeo[1] name = matokeo[2] subjects = matokeo[3] # Assuming subjects are already formatted correctly parsed_results.append({'index': index, 'sex': sex, 'name': name, 'subjects': subjects}) print("Split result:", parsed_results) # Add this line for debugging # else: # print("Error: Split result doesn't contain enough elements") # Add this line for debugging # print("Results:", result) return parsed_results " it should pass to model and take each data by its own in the result templates the scrapped data to be resenterd in the table form at the result templates so as to be inthe separate like this "index: ps022013/001 sex: M name: fname lname subjects:'Kisw - B, Engl - B, Maarifa - B, Hisabati - A, Science - B, Average Grade - B' -
Why does Django admin page and the rest of my pages' CSS files and images are not found?
the GET method returns 404 in the console even though its searching in the correct file path. EDIT: i found another post that said i should turn on the DEBUG in the settings.py file. AND IT WORKED!! now after trying to turn it back to False, it still worked as expected. so the second question is why did it not work on the first try? i made sure the static paths in the settings.py file are correct but it seems the issue is with django itself since the django admin page doesn't show CSS either. i tried python manage.py collectstatic and it didn't work i tried restarting the server multiple times and still -
Error: Redirect URI Mismatch when Integrating Microsoft Authentication with Django
I am trying to integrate Microsoft authentication with my Django app deployed on Azure Web App using the django_auth_adfs package. However, I encountered an error regarding a mismatch in the redirect URI. I have followed the documentation provided by django_auth_adfs for configuring Azure Active Directory integration. In my Azure portal, I registered the application and added http://localhost:8000/oauth2/callback to the Web Redirect URLs as instructed. Web Redirect URLs When attempting to authenticate, I receive the following error message: The redirect URI 'http://127.0.0.1:8000/oauth2/callback' specified in the request does not match the redirect URIs configured for the application. Make sure the redirect URI sent in the request matches one added to your application in the Azure portal. Here is my settings.py configuration related to django_auth_adfs: INSTALLED_APPS = [ ... 'django_auth_adfs', ] MIDDLEWARE = [ ... 'django_auth_adfs.middleware.LoginRequiredMiddleware', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'django_auth_adfs.backend.AdfsAccessTokenBackend', ] LOGIN_REDIRECT_URL = '/' LOGIN_URL = 'django_auth_adfs:login' LOGOUT_REDIRECT_URL = '/' # django-auth-adfs settings AUTH_ADFS = { 'AUDIENCE': config('MICROSOFT_AUTH_CLIENT_ID'), 'CLIENT_ID': config('MICROSOFT_AUTH_CLIENT_ID'), 'CLIENT_SECRET': config('MICROSOFT_AUTH_CLIENT_SECRET'), 'CLAIM_MAPPING': {'first_name': 'given_name', 'last_name': 'family_name', 'email': 'upn'}, 'GROUPS_CLAIM': 'roles', # or None 'MIRROR_GROUPS': True, 'USERNAME_CLAIM': 'upn', 'TENANT_ID': config('MICROSOFT_AUTH_TENANT_ID'), 'RELYING_PARTY_ID': config('MICROSOFT_AUTH_CLIENT_ID'), } ADFS_REDIRECT_URI = 'http://localhost:8000/oauth2/callback' What could be causing this redirect URI mismatch error despite configuring the correct redirect URI … -
Django: how to make a standard input form to conditionally insert OR update many-to-many records?
I am trying to figure out a way to update or insert new many-to-many records of a Product into an Order through an intermediary model ProductOrder. I want to have a standard form with all Products and their respective quantities poQty. A standard form (assuming to have 4 Products in total) is used to update existing Order records. If an order has 2 Products associated to it, the form should: include additional products if poQty>0 change existing products if poQty has changed do nothing if non-existing Products remain with standard poQty=0 I am currently getting the following error message when I try to submit the form: {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}] I would appreciate some help on that... THANKS ! Further details: models.py class ProductClass(models.Model): classDescription = models.CharField(max_length=255, verbose_name='Type', unique=True, null=True) classPrint = models.BooleanField(default=True, verbose_name='Print?') class Meta: verbose_name_plural = 'Product Classes' def __str__(self): return self.classDescription class Product(models.Model): prodclassQuery = models.ForeignKey(ProductClass, on_delete=models.PROTECT, verbose_name='Product Class', default=1) prodDescription = models.CharField(max_length=255, verbose_name='Product') prodPrice = models.DecimalField(max_digits=6, decimal_places=2, verbose_name='Price') … -
Why is permission error returned when sending creating FileResponse in Django?
In temp folder there is a temporary file called video.mp4 which is meant to be created, then sent to user as attachment and then deleted. The following code returns PermissionError: [WinError 32] for this line: os.remove(file_path). Why ? Am i deleting file too early ? def download_video(request): if request.method == 'POST': link_input_data = request.POST.get('link_input_field') # todo change to use django forms later download_cda.start_download(link_input_data) file_path = "temp\\" + "video.mp4" response = None try: file = open(file_path, "rb") response = FileResponse(file, as_attachment=True, filename="video.mp4") except Exception as e: print(e) # todo add exception code finally: os.remove(file_path) return response else: form = UrlForm() return render(request, 'index.html', {"url_form": form}) I couldn't find anything for this in docs: [FileResponse] (https://docs.djangoproject.com/en/5.0/ref/request-response/#django.http.FileResponse) -
not all arguments converted during string formatting when trying to execute mssql stored procedure from django
My procedure consists of inserting the data into a table in the database from REST API. p1,p2,p3 are the parameters coming from the user interface P1,P2,P3 are my stored procedure's parameters. Here is my code def test(request): if request.method == "POST": with connection.cursor() as cursor: P1 = request.data["p1"] P2 = request.data["p2"] P3 = request.data["p3"] params = (P1,P2,P3) print(params) try: cursor.execute("{CALL [dbo].[myStoredProcedure]}",params) if cursor.return_value == 1: result_set = cursor.fetchall() print(result_set) finally: cursor.close() return Response({"msg":"post"}) else: return Response({"msg": "get"}) when I add parameters like this: cursor.execute("{CALL [dbo].[myStoredProcedure] (P1,P2,P3)}")"P1","P2","P3" are inserted in the database but not the value of these parameters. How to solve this problem ? -
Accessing Images in media/ folder In Django, as public url
I can access the image on the local machine as http://127.0.0.1:8000/media/taj.jpg in the browser. How can I access the same image publicly in the browser? Like url: http://49.128.160.80:8000/media/taj.jpg -
How can I optimize raw queries to a MySQL in django
I'm new to Django, this is my code, what happens is that when that view is executed, it takes too long to load, approximately 15 seconds and that's a lot, how could I optimize this so that it doesn't take too long? from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.db import connections import datetime @login_required def show_data_tbl_form_gen(request): with connections['mysql_db'].cursor() as cursor: cursor.execute("SELECT * FROM tbl_form_gen ORDER BY time DESC") datos = cursor.fetchall() datos = [list(dato) for dato in datos] for dato in datos: id_granja = dato[4] with connections['mysql_db'].cursor() as cursor: cursor.execute("SELECT NombreFinca FROM tbl_granjas WHERE CodigoFinca = %s", [id_granja]) nameFarm = cursor.fetchone() if nameFarm: dato.append(nameFarm[0]) else: dato.append("Granja Desconocida") id_colab=dato[2] with connections['mysql_avicon_bluehost'].cursor() as cursor: cursor.execute("SELECT Nombres, Apellidos FROM tblEmpleados WHERE Rol = %s", [id_colab]) nameColab = cursor.fetchone() if nameColab: # union names and lastnames full_name = f"{nameColab[0]} {nameColab[1]}" dato.append(full_name) else: dato.append("Colaborador Desconocido/a") #print list print("Array de datos con nombres de granja:", datos) return render(request, 'app_web_pofapp/select.html', {'datos': datos}) def detalles(request, id): with connections['mysql_db'].cursor() as cursor: cursor.execute("SELECT * FROM tbl_form_gen WHERE id_forms_generators = %s", [id]) formulario = cursor.fetchall() # convert formulario = [list(dato) for dato in formulario] # get names for dato in formulario: id_granja = dato[4] with connections['mysql_db'].cursor() as cursor: … -
Django sync_to_async blocking event_loop on ORM queries?
So I am using asyncio and Django and to use Django's ORM you need to either use asnyc methods or wrap the ORM calls in sync_to_async. I am having some questions however understanding if while I am waiting for the response from the database the event loop is freed to do other operations ex: def sync_function(user_id, name): user = User.objects.get(id=user_id) last_name_user = User.objects.filter(name=name).last() return user, last_name_user If I do async def async_function(user_id, name): user, last_name_user = await sync_to_async(sync_function)(user_id, name) will my event loop be free to do other CPU bound operations while those querys are done? I am also aware there are aget and alast methods but it seems all they do is wrap the actual method with sync_to_async so I'd also like to know if there would be a difference between the example I provided earlier and async def async_function(user_id, name): user = await User.objects.aget(id=user_id) last_name_user = await User.objects.filter(name=name).alast() I read a bit about thread_sensitive parameter in sync_to_async is my understanding that by default being True it means that function wrapped will be ran in the same thread and thus the event loop wont be able to run other tasks, and if it is False it could be parallelized? -
Download image to client's PC django
''' class Archivo(models.Model): Archivo = models.ImageField(upload_to="Seccion1") def descarga1(archivo_nombre): if archivo_nombre.endswith(".jpg"): return True return response ''' ''' class Jpgtopng(View): def get(self,request): return render(request,"Pngtojpg.html",{"form":Formext}) def post(self,request): Formulario = Formext(request.POST,request.FILES)#?Recibimos datos del formulario if Formulario.is_valid(): imagen = Formulario.cleaned_data["Archivo"] imagen_nombre = imagen.name if Formulario.Extension(imagen_nombre): Formulario.save() self.Descargar(imagen) else: return HttpResponse("Extension incorrecta") else: #? En caso de no ser valido reenviamos el formulario return render(request,"Pngtojpg.html",{"Formu":Formulario}) return HttpResponse("Hubo un error") def Descargar(archivo): Nombre = archivo.name return Fileresponse(open(Nombre,"rb"),as_attachment=True, filename=Nombre) ''' ''' from django.urls import path from .views import Jpgtopng,Pngtojpg urlpatterns =[ path("Cambiopngajpg/",Jpgtopng.as_view(),name="JpgtoPng"), path("Cambiojpgtopng/",Pngtojpg.as_view(),name="Pngtojpg"), ] ''' For some reason the download never starts but the verification of the form and the extension do work -
Pre-Signed URL with boto3 and django-storages incorrect filepath
For a file upload feature, I'm trying to set a FileField in Django using a presigned url but when the field is saved it seems that the aws bucket name is being added into the url so when I try to access the file from the django admin I get a Key does not exist error. For the upload I first generate a presigned url on the backend: try: s3_client = boto3.client( "s3", region_name=settings.AWS_S3_REGION_NAME, config=Config(signature_version="s3v4"), aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, ) s3_response = s3_client.generate_presigned_url( "put_object", HttpMethod="PUT", ExpiresIn=settings.AWS_SIGNED_URL_DURATION, Params={ "Bucket": settings.AWS_STORAGE_BUCKET_NAME, "Key": f"{user.uuid}/{instance.uuid}/{payload.dict().get('filename')}", "ContentType": "application/octet-stream", }, ) except ClientError as e: logger.exception(e) return 500, {"message": "Something went wrong."} This is then used by the frontend client to upload the file - this all works ok and uploads a file to the following url: https://<BUCKET_NAME>.s3.<BUCKET_REGION>.amazonaws.com/<USER_UUID>/<INSTANCE_UUID>/<FILE_NAME> (I have checked in s3 and the file is there.) The frontend then sends a patch request to update the DB with the url once the upload has been successful. The data looks like this: {"file_field": "<USER_UUID>/<INSTANCE_UUID>/<FILE_NAME>"} However, when I try to access the file from the django admin (or when I retrieve the instance data from my REST API), the file field shows a different url: https://<BUCKET_NAME>.s3.<BUCKET_REGION>.amazonaws.com/<BUCKET_NAME>/<USER_UUID>/<INSTANCE_UUID>/<FILE_NAME> (Notice the … -
How to start and complete an atomic transaction in MySQL by using Django 5.0.3?
I want to save a CSV (with 50k rows) as a MySQL table in Django. I wrote the model and I started the atomic transaction from the post request (runned by ajax async submit from the template). The problem is that the transaction is interrupted by the StateReloader and it does not continues. Is it possible to run the transaction in background and let it to complete? Here a small version of my code: # file: models.py from django.db import models, transaction class MyManager(models.Manager): @transaction.atomic def create_models(self, file, callback=None): if callback is not None: transaction.on_commit(callback) with open(file, "r") as fp: lines = map(str.strip, fp.readlines()) lines = map(lambda x: x.split(";"), lines) lines = list(lines) headers = lines[0] print("Writing table with {} lines...".format(len(lines) - 1)) # 50k lines for i, line in enumerate(lines[1:]): for j in range(len(headers)): print("Saving line #{}".format(i), end="\r"). # ends at line 800 before the StateReloader self.create(row=i + 1, header=headers[j], value=line[j]) print() return True class MyModel(models.Model): row = models.IntegerField(null=False, blank=False) header = models.CharField(max_length=255, null=False, blank=False) value = models.CharField(max_length=255, null=False, blank=False) objects = MyManager() def __str__(self) -> str: return f"{self.header} = {self.value} on row {self.row}" # file: views.py from django.http import JsonResponse from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin … -
How to return a json containing a model object, as well as all the models related to it in Django
I have been working on a project in django, and I am stuck trying to extract some concepts, and parse their rules or complex rules depending on the concept's instance_type, and the rule clauses for each rule, and then put them in a json like format. This is the model structure to give you a quick view of the database and this is how its implementation in short: class RuleClause(models.Model): name = models.CharField(max_length=100, null=False, default="") type = models.CharField(max_length=200,choices=clauses_types_choices, default="StatsRuleClause") class Rule(models.Model): name = models.TextField(default=DEFAULT_NAME) # , unique=True) description = models.TextField(null=True, blank=True) clauses = models.ManyToManyField(RuleClause, through="RuleClauseRule") class ComplexRule(models.Model): name = models.TextField(default=DEFAULT_NAME, unique=True) description = models.TextField(null=True, blank=True) rules = models.ManyToManyField(Rule, through="RuleComplexRule") class Concept(models.Model): name = models.CharField(max_length=200, default=DEFAULT_NAME, unique=True) instance_id = models.IntegerField(default=0) instance_type = models.CharField(max_length=200, choices=concept_type_choices) And this is the desired output: {"concepts": [ { "name": "Concept_1", "instance_type": "rule" "instance_id": { "name": "rule_1", "description": "", "clauses": [ { "name": "Clause_1", "type": "" }, { "name": "Clause_2", "type": "" }] } }, { "name": "Concept_2", "instance_type": "complex_rule" "instance_id": { "name": "complex_rule_1", "description": "", "rules": [ { "name": "Rule_2", "description": "", "clauses": [ { "name": "clause_1", "type": "" }, { "name": "clause_4", "type": "" }] }] } } ]} Important: Keep in mind I am …