Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to detect selected text from a PDF using Python in a Django application?
I have a Python script that successfully detects selected text from a PDF file using the xdotool and pyperclip libraries. Here's the script: import time import os import subprocess import pyperclip def get_selected_text(): subprocess.run(['xdotool', 'key', 'ctrl+c']) time.sleep(1) return pyperclip.paste() if __name__ == "__main__": pdf_filepath = 'class3english.pdf' subprocess.Popen(['xdg-open', pdf_filepath]) while True: selected_text = get_selected_text() if selected_text: print("Selected text:", selected_text) time.sleep(2) However, when I try to integrate this script into my Django application, it doesn't detect the selected text from the PDF. Instead, it captures text from the clipboard. I want to be able to detect text that the user has actively selected within the PDF viewer. Is there a way to achieve this within a Django application? How can I modify my approach to capture only the selected text from a PDF when running within a Django environment? -
Problem with Django form field styling upon error
I'm building my first website with Django and I have encountered what I think is a really weird problem. I have a form in the page, and I want that, if the user inputs invalid data in one of its fields, that field is marked with a specific CSS style. What I have done is write a validation method (a "clean()" method) that checks the input provided by the user. If it doesn't pass the validation, the class "error" is added to the widget of that input. Then, using CSS, I give that .error class some specific styling. Here is the problem: the error style is not applied correctly to the fields "name", "last name" and "email" of the form. For instance, when you input an invalid last name, both the field "last name" and "name" get highlighted in red, and when you input an invalid email address, both the "email" and the "name" fields get highlighted. I have gone over the "forms.py" file a thousand times and I can't figure out what's wrong. Here is the code of the "forms.py" file: from django import forms from .models import Appointment class AppointmentForm(forms.ModelForm): class Meta: model = Appointment fields = ['name', … -
client_is_modern return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9' TypeError: 'NoneType' object is not subscriptable
{ "error": "Input nbnb.csv of type: <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> is not supported." } if not self.origin_server or self.client_is_modern(): File "C:\Program Files (x86)\lib\wsgiref\handlers.py", line 358, in client_is_modern return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9' TypeError: 'NoneType' object is not subscriptable tried spliting that code but still its not working -
Django / Websocket : How to get all actives `websockets`?
I would like get all websockets opened with a consumer like an .objects.all(). It is possible like this ? or with another method to "list" all actives websockets ? Thank you everyone in advance for answers ! I found nothing about that in the documentation or anything else, but if a thing like that exists, it can very useful. -
NSUrlErrorDomain -1004 on Django Backend hosted by AWS (Route 53 + ELB) on iOS
Noticed today that some users are getting NSUrlErrorDomain (code -1004) by accessing our website, which is managed by ECS + ELB (6 rules) + Route 53. Obviously, those domains have ssl, but accessing the website on Safari and Firefox (iOS), I'm automatically redirected to the "http" version, making me get the "NSUrlErrorDomain" error. If I type the website starting "https", it goes normally, and it only happens on iOS (didn't test Android, but on Chrome doesn't happens), and also don't happen on Desktop, and on MacOS only happens using Safari browser. Any clue of what is that? -
CSRF verification failed. Request aborted with JWT token in Django RestAPI
I am currently encountering a 403 Forbidden error due to CSRF verification failure when making a POST request to my Django app's API endpoint, even while using a JWT token for authentication. I've attempted to disable CSRF protection for the API while maintaining it for the admin panel using a custom middleware, but the error persists. Below is the relevant configuration in my settings.py and views.py. I've tried to disable CSRF checks for my API endpoints using custom middleware, as well as the decorators @method_decorator(csrf_exempt) and @csrf_exempt, but the CSRF requirement still seems to be enforced. Here's an overview of the steps I've taken: settings.py: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', "django.middleware.common.CommonMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "spBE.middlewares.disable_csrf.DisableCSRFOnAPI", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ALLOWED_HOSTS = ['*'] CSRF_TRUSTED_ORIGINS = ['http://localhost:1337','http://localhost:8000','http://10.126.2.27:8000','http://10.126.2.27:1337'] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from drf_yasg.views import get_schema_view from drf_yasg import openapi from rest_framework.permissions import AllowAny from rest_framework_simplejwt.authentication import JWTAuthentication schema_view = get_schema_view( openapi.Info( title="Domocek API", default_version='v1.1', description="Breakpoints", terms_of_service="https://app.slack.com/client/T04RV3CLJ2W/C06KV8FSY3X", contact=openapi.Contact(email="nikita@gmail.com"), license=openapi.License(name="License"), ), public=True, permission_classes=(AllowAny,), authentication_classes=(JWTAuthentication,), url='http://10.126.2.27:1337/', ) urlpatterns = [ path("admin/", admin.site.urls), path('api/', include('api.urls')), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ] if settings.DEBUG: urlpatterns … -
DigitalOcean Spaces and Django/Wagtail - SSL error on upload
I have a Django/Wagtail app running on DigitalOcean AppPlatform and am trying to enable Spaces for media storage. The app builds just fine, but image uploads from the app fail every time with the following error: [2024-04-17 21:40:33] botocore.exceptions.SSLError: SSL validation failed for https://mybucket.mybucket.nyc3.digitaloceanspaces.com/original_images/Screenshot_2024-04-01_at_2.10.53PM.png hostname 'mybucket.mybucket.nyc3.digitaloceanspaces.com' doesn't match either of '*.nyc3.digitaloceanspaces.com', 'nyc3.digitaloceanspaces.com' That URL shows my bucket name repeated twice (note "mybucket.mybucket"), but I can't tell where or why it's repeating. In my production.py settings file, I'm using env vars set on the DigitalOcean side, and have triple checked that those vars are correct. I've also tried hardcoding them instead just to be sure, with the same error. AWS_ACCESS_KEY_ID = os.getenv('SPACES_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('SPACES_SECRET_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('SPACES_BUCKET_NAME') AWS_DEFAULT_ACL = 'public-read' AWS_S3_ENDPOINT_URL = os.getenv('SPACES_ENDPOINT_URL') AWS_S3_REGION_NAME = os.getenv('SPACES_REGION') AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_ADDRESSING_STYLE = 'virtual' AWS_LOCATION = os.getenv('SPACES_FOLDER') DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' MEDIA_URL = '%s/' % (AWS_S3_ENDPOINT_URL) I've added & installed the following in the app (including storages under INSTALLED_APPS): boto3 (v1.34.84) botocore (v1.34.84) django-storages (v1.14.2) And have a storages_backends.py with the following: from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): location = 'static' class MediaStorage(S3Boto3Storage): location = '' Any ideas on what is causing that … -
Integrating Auth0 with the Django admin interface
I have a Django application and I am trying to change the authentication flow to use Auth0. Unfortunately, I haven't found any tutorials on how to implement this. Currently, users log in with username/password and receive a session token. I would like to change this so users are redirected to Auth0, login there, receive the session credential, and are then redirected to the admin UI. Does anyone have any experience with this? I am very stuck. -
Error when adding object using django admin "incorrect padding"
I was adding an Ad in the admin interface to use to test some template code. Previously, yesterday, I was able to add Ads no problem. I log into admin, select add a new Add, then enter text into the CharField and TextFields of the model. Worked always before today. Now, I get an error. Error at /admin/ads/ad/add/ Incorrect padding I am using pythonanywhere. Below is the traceback: Environment: Request Method: POST Request URL: https://chabnet.pythonanywhere.com/admin/ads/ad/add/ Django Version: 4.2.7 Python Version: 3.10.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django_extensions', 'crispy_forms', 'crispy_bootstrap5', 'rest_framework', 'social_django', 'taggit', 'home.apps.HomeConfig', 'ads.apps.AdsConfig', 'knightshirt.apps.KnightshirtConfig'] Installed 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', 'social_django.middleware.SocialAuthExceptionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware'] Traceback (most recent call last): File "/home/chabnet/.virtualenvs/django4/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/chabnet/.virtualenvs/django4/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/chabnet/.virtualenvs/django4/lib/python3.10/site-packages/django/contrib/admin/options.py", line 688, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/chabnet/.virtualenvs/django4/lib/python3.10/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) File "/home/chabnet/.virtualenvs/django4/lib/python3.10/site-packages/django/views/decorators/cache.py", line 62, in _wrapper_view_func response = view_func(request, *args, **kwargs) File "/home/chabnet/.virtualenvs/django4/lib/python3.10/site-packages/django/contrib/admin/sites.py", line 242, in inner return view(request, *args, **kwargs) File "/home/chabnet/.virtualenvs/django4/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1886, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/home/chabnet/.virtualenvs/django4/lib/python3.10/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/home/chabnet/.virtualenvs/django4/lib/python3.10/site-packages/django/utils/decorators.py", line 134, … -
Adding HTML Button to Editor Buttons in Wagtail
I am having an issue wrapping my head around adding a custom button in Wagtail to the RichTextEditor buttons, where when clicked, a user of the editor is able to add a link with an html button. The code I used for this in TinyMCE was originally provided here: https://dev.to/codeanddeploy/tinymce-add-custom-button-example-399m But I can't figure out how to register a hook in Wagtail to implement that type of functionality. There is a similar example here, but I can't figure out how to enable the actual button to be rendered with style we predefine like I had done in TinyMCE editor. Here is an example that works fine for this use case, but I am hoping there is a simple one with the idea to add buttons like I had done with TinyMCE: https://erev0s.com/blog/wagtail-list-tips-and-tricks/#add-a-code-button-in-the-rich-text-editor Here is the code from that post: from wagtail.core import hooks @hooks.register("register_rich_text_features") def register_code_styling(features): """Add the <code> to the richtext editor and page.""" # Step 1 feature_name = "code" type_ = "CODE" tag = "code" # Step 2 control = { "type": type_, "label": "</>", "description": "Code" } # Step 3 features.register_editor_plugin( "draftail", feature_name, draftail_features.InlineStyleFeature(control) ) # Step 4 db_conversion = { "from_database_format": {tag: InlineStyleElementHandler(type_)}, "to_database_format": {"style_map": {type_: … -
Upload files from Nextjs to Django backend using api route
I'm using Django (DRF) in the backend and Next.js 14 in the frontend. I can upload small files without any issue, but when the file size exceeds around 100kb, the API request gets stuck in "pending" status. Here's how the form looks in page.js: const handleSubmit = async (e) => { e.preventDefault(); const formData = new FormData(); if (avatar) formData.set("avatar", avatar); formData.set("bio", bio); const res = await fetch(`/api/auth/profile/`, { method: "POST", body: formData, }); const updatedProfile = await res.json(); }; And here's how the api/route.js file looks: export async function POST(request, res) { const access = await getAccessTokenServer(); if (!access) return NextResponse.json( { detail: "Kullanıcı girişi bulunamadı" }, { status: 401 } ); const formData = await request.formData(); const response = await fetch( `${process.env.API_URL}/api/users/me/profile_update/`, { method: "POST", headers: { Authorization: `Bearer ${access}` }, body: formData, } ); When I directly send the request to Django backend from page.js file, there's no problem with uploading large files. However, when I send the request to the api/route address and then to Django, the file doesn't reach Django. I tried to set config for api route like this. `export const config = { api: { bodyParser: { sizeLimit: '10mb', }, }, // Specifies … -
Getting 401 unauthorised when trying to access JWT authenticated page in Django even after generating token
I'm a student trying to teach myself JWT authentication. I created a basic log in page and after logging in the user should see a welcome page that says Welcome {username}. However even after logging in, the welcome page says Welcome GET /welcome/ HTTP 401 Unauthorized Allow: GET, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Bearer realm="api" { "detail": "Authentication credentials were not provided." } My code looks like this: views.py from django.http import JsonResponse from django.shortcuts import render, redirect from loginapp.models import User from rest_framework.decorators import api_view, permission_classes, authentication_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework_simplejwt.tokens import RefreshToken from django.contrib.auth import authenticate from rest_framework_simplejwt.authentication import JWTAuthentication from django.urls import reverse def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') print("Username:", username) print("Password:", password) user = User.objects.filter(username=username).first() #user = authenticate(username=username, password=password) if user is not None and user.password == password: refresh = RefreshToken.for_user(user) token = str(refresh.access_token) response = JsonResponse({'message': 'Login successful'}) response['Authorization'] = f'Bearer {token}' return response else: return JsonResponse({'error_message': 'Invalid username or password.'}, status=400) else: return render(request, 'login.html') @api_view(['GET']) @permission_classes([IsAuthenticated]) def welcome(request): username = request.user.username return Response({'message': f'Welcome, {username}!'}) my urls.py looks like this: from django.urls import path from loginapp import views from rest_framework_simplejwt.views … -
Deploying django app using almalinux 8 plesk
Recently i have created a website using django. But when it is time for deploying it became a nightmare. I am pretty new in these stuff. Since this is a productuon promissed for someone else i have to do it done. I wonder if anyone could do it for me? I have a vps server running using plesk panel. And an almalinux 8 as os. Any help would absolutely work. -
Django annotate over multi records forignkeys
I Work on a KPI system in which every manager can put specific questions for each user and answer them every month from 1 to 10 we have 4 departments, and every department says to have 4 question these answers have to be calculated to return the % number for each department Models # question to answer every month class Question(models.Model): department = models.CharField(max_length=100, choices=USER_TYPE) question = models.CharField(max_length=100) def __str__(self): return f"{self.question}" # create every 01-month celery class Kpi(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="kip_for") created_at = models.DateField() class Meta: unique_together = ("user", "created_at") def __str__(self): return f"{self.user} for Month {self.created_at.month}" # group the answers by department class DepartmentsKPI(models.Model): department = models.CharField(max_length=100, choices=USER_TYPE) kpi = models.ForeignKey( Kpi, on_delete=models.CASCADE, related_name="department_kpi" ) class Answer(models.Model): question = models.ForeignKey( Question, on_delete=models.CASCADE, related_name="answer_for" ) score = models.PositiveSmallIntegerField(default=0) comment = models.TextField(null=True, blank=True) kpi_answers = models.ForeignKey( DepartmentsKPI, on_delete=models.CASCADE, related_name="department_answers", ) the problem is when I apply the annotation over the KPI model to sum the answer score for each department, the result becomes ungrouped so I have to group them by a unique value in my case the username def get_kpi_range(*, year, month): queryset = ( KPIRepository.filter_kpis( created_at__year=year, created_at__month=month, ) .prefetch_related("department_kpi__department_answers") .annotate( score=Sum("department_kpi__department_answers__score") / Count("department_kpi__department_answers"), department=F("department_kpi__department"), ) .values("id", … -
About page on Django app is showing Page not found
Tried running about page on a Django project using sublime text editor. The project shows page not found each time i refresh the browser. I have tried every method i came across. from.django contrib import admin from django.urls import path from . import views urlpatterns=[ path('admin/' admin.site.urls) path('about/' views.urls) ]` I expect the project to show the content of the about page. Without returning the 404 error response. from django.http import HttpResponse def index(request): return HttpResponse("This is about page.") -
How to Clean an Ubuntu Server Previously Used for Hosting a Django Project?
I have an Ubuntu server that previously hosted a Django project. I want to clean the server and prepare it for a new project deployment. This includes removing all project-specific files, configurations, and any leftover services related to the old project. Ideally, I'd like to get the server close to its initial state (without reinstalling the OS). I followed the documentation provided by DigitalOcean to set up Django with Postgres, Nginx, and Gunicorn on Ubuntu for the old project. However, now I need to remove all traces of the old project from the server. I'm expecting guidance on how to properly clean up the server, including removing project files, configurations, and services, without affecting the OS or other applications running on the server. DigitalOcean documentation -
Errors with Django 4.2 and Spatialite 5
I am upgrading an application from Django 3.2 to 4.2, which uses postgis in production, and spatialite when running unit tests. Running the tests on this application, I'm getting this error: django.db.utils.OperationalError: error in trigger ISO_metadata_reference_row_id_value_insert: no such column: rowid make: *** [django.mk:49: test] Error 1 This problem is documented in this ticket, and seems to be an issue with using Django 4.2 and Spatialite 5: https://code.djangoproject.com/ticket/32935 One of the workarounds looks like executing this command in the spatialite database: ./manage.py shell -c "import django;django.db.connection.cursor().execute('SELECT InitSpatialMetaData(1);')"; However, after I run this command, I am still getting the no such column: rowid error. Has anyone else run into this? I am using Django 4.2.11, sqlite 3.42.0, libspatialite 5.0.1, python 3.12.2 on Fedora Linux. -
Error when using python3 manage.py makemigrations [closed]
I keep getting this error and don't know what's wrong or what to do. Traceback (most recent call last): File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/urls/resolvers.py", line 717, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/core/management/base.py", line 453, in execute self.check() File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/core/management/base.py", line 485, in check all_issues = checks.run_checks( File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/urls/resolvers.py", line 495, in check messages.extend(check_resolver(pattern)) File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/urls/resolvers.py", line 494, in check for pattern in self.url_patterns: File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/urls/resolvers.py", line 725, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'djangoapp.urls' from '/home/project/xrwvm-fullstack_developer_capstone/server/djangoapp/urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the … -
Why the data batch size for loop failing for Insert API in python Django?
We are using 3rd party API to pull data and enabled pagination, hence the amount of data coming in are huge. Some times 12000 records at a time in a list. We are using mySQL DB, and it fails when it receives that amount of data at a time. So, as temporary solution I wanted to implement the "batch size" concept as below: batch_size = 3 for batch in range(0, len(payload), batch_size): batch_data = payload[batch:batch + batch_size] Below is the POST method code snippet where we are getting the data source and its format , and how I am passing it. def post(self, request): data = fetch_data.get(request=request) try: if data.status_code == status.HTTP_200_OK: payload = data.data payload["token_id"] = token_id payload["org"] = org api_log( msg=f"TOtal cont data from xyz : {json.dumps(payload)}" ) api_log( msg=f"Size of cont data from xyz : {len(json.dumps(payload))}" ) api_log( msg=f"Length of cont data to db: {len(payload)}" ) api_log( msg=f"Total cont data to DB: {payload}" ) url = ("http://example.com") batch_size = 3 api_log(msg=f"[BATCH SIZE]:: {batch_size}") for batch in range(0, len(payload), batch_size): api_log(msg=f"[BATCH SIZE]:: {batch_size}") api_log(msg=f"[BATCH]:: {batch}") batch_data = payload[batch:batch + batch_size] api_log(msg=f"[BATCH DATA]:: {batch_data}") response_data = requests.post( url, json=batch_data, ) if response_data.status_code == status.HTTP_201_CREATED: api_log( msg="data inserted successfully" ) … -
Django Rest API - handling max_decimal_places more gracefully
Using Django Rest Framework and having a model that contains a decimal field like this: rate = models.DecimalField(max_digits=7, decimal_places=2) If a rate value is submitded with more than 2 decimal places I get a validation error with code "max_decimal_places". I would like to handle things more gracefully and instead of raising an error I would like to round the rate to 2 decimal places. What's the best or even a good way of doing this. Overriding validation? Other options? Thanks Stephan -
Django PyCryptodome AES decryption - ValueError: Padding is incorrect
I am trying to encrypt incoming files and than decrypt them later. I was following the documentation for how to use AES with CBC mode for decryption and encryption. My view for uploading and encrypting file: @router.post("/upload_files") def upload_files(request, file: UploadedFile = File(...)): save_file = operations.aes_encryption(user_id=request.auth.id,file=request.FILES.get('file')) def aes_encryption(self,user_id,file): user = UserQueries.get_user(id=user_id) key: bytes = bytes(user.key, "utf-8") path: str = user.path save_file = self._encrypt_file(file,key,path,user) return save_file def _encrypt_file(self,file,key,path,user): file_content = file.read() cipher = AES.new(key, AES.MODE_CBC) ct_bytes = cipher.encrypt(pad(file_content, AES.block_size)) iv = b64encode(cipher.iv).decode('utf-8') ct = b64encode(ct_bytes).decode('utf-8') with open(str(settings.BASE_STORAGE_DIR)+"/"+path+file.name,"wb") as f: f.write(ct.encode('utf-8')) return save_metadata This code works like it should it encrypts the file and stores it in directory. My key and iv is stored in database as string. This is my decryption function where I am having trouble: def aes_decryption(self,request, file_id): user = UserQueries.get_user(id=request.auth.id) file = FileQueries.get_file_data(id=file_id) iv = b64decode(file.iv) key = b64decode(user.key) with open(str(settings.BASE_STORAGE_DIR)+"/"+file.path,"rb") as f: cipher = f.read() decrypt_file = self._decrypt_file(iv,key,cipher_text=cipher) def _decrypt_file(self,iv,key,cipher_text): cipher = AES.new(key, AES.MODE_CBC, iv) pt = unpad(cipher.decrypt(cipher_text), AES.block_size) When calling the decryption I am getting this error: Padding is incorrect. Traceback (most recent call last): File "/Users/Library/Caches/pypoetry/virtualenvs/cloud-hub-backend-y-HyWMBZ-py3.11/lib/python3.11/site-packages/ninja/operation.py", line 107, in run result = self.view_func(request, **values) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/Documents/cloud_project/backend/cloud_hub_backend/cloud_hub_backend/apps/file_storage/views.py", line 67, in download_files file, content_type, file_name = … -
Django ORM: .filter() finds record but .get() with same query parameters does not
I am doing an ORM query using the .filter without the timeframe specified which returns two records. then I print those record column values to ensure I am not making any mismatches but then when I use the exact same values on the .GET method I get DoesNotExist error even though it just printed that record. Please verify if your comment is valid based on the printed statements before submitting stupid comments like: mAyBe yOu mAde A sPelLinG erRoR?! here is are the prints: Filter Query: timeframe=H4, symbol=XAUUSD, time=2024-04-10 14:00:00+00:00 Filter Record 2: XAUUSD, 2024-04-10 14:00:00, H4 GET Query: timeframe=H4, symbol=XAUUSD, time=2024-04-10 14:00:00+00:00 No record found. @csrf_exempt @require_http_methods(["POST"]) def get_label_data(request): data = json.loads(request.body) data = data.get('data') timestamp = data.get('timestamp') symbol_name = data.get('symbol') label_name_str = data.get('label_name') timeframe = data.get('timeframe') symbol = Symbol.objects.get(name=symbol_name) datetime_stamp = datetime.fromtimestamp(timestamp, tz=pytz.UTC) print(f"Filter Query: timeframe={timeframe}, symbol={symbol_name}, time={datetime_stamp}") forex_ohlc = ForexOHLC.objects.filter(symbol=symbol, time=datetime_stamp) forex_ohlc = list(forex_ohlc)[1] print(f"Filter Record 2: {forex_ohlc.symbol.name}, {forex_ohlc.time}, {timeframe}") print(f"GET Query: timeframe={timeframe}, symbol={symbol_name}, time={datetime_stamp}") try: forex_ohlc = ForexOHLC.objects.get(symbol=symbol, time=datetime_stamp, timeframe=timeframe) except ForexOHLC.DoesNotExist: print("No record found.") except ForexOHLC.MultipleObjectsReturned: print("Multiple records found.") except Exception as e: print(f"An unexpected error occurred: {e}") try: labels = TickLabel.objects.get(forex_ohlc=forex_ohlc, symbol=symbol, label_name__name=label_name_str) return JsonResponse({ 'label_name': labels.label_name.name, 'label_type': labels.label_type.name, 'hasLabel': True }) except TickLabel.DoesNotExist: … -
Exception Type: ValueError: node array from the pickle has an incompatible dtype
So I copied a DjangoML project from Github. The ML model is essentially a diagnosis system that predicts whether or not a patient is at risk based on the values of their blood tests. I'm running this project locally in VSCode but have yet to deploy the backend/ML model. I encountered this problem while attempting to forecast the outcome in the web browser. I'm using Python 3.11.0 for this project. The requirements.txt file includes: asgiref==3.5.0 Django==4.0.3 joblib==1.1.0 numpy~=1.26.4 pandas==2.2.2 python-dateutil==2.8.2 pytz==2022.1 scikit-learn==1.0.2 scipy==1.8.0 six==1.16.0 sklearn==0.0 sqlparse==0.4.2 threadpoolctl==3.1.0 tzdata==2021.5 `Traceback (most recent call last): File "D:\Django_MachineLearning_HealthcareApp-main\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\Django_MachineLearning_HealthcareApp-main\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Django_MachineLearning_HealthcareApp-main\backend\views.py", line 76, in lpredictor result = ValuePredictor(llis, 7, mname) File "D:\Django_MachineLearning_HealthcareApp-main\backend\views.py", line 60, in ValuePredictor trained_model = joblib.load(rf'{mdname}_model.pkl') File "D:\Django_MachineLearning_HealthcareApp-main\venv\Lib\site-packages\joblib\numpy_pickle.py", line 658, in load obj = _unpickle(fobj, filename, mmap_mode) File "D:\Django_MachineLearning_HealthcareApp-main\venv\Lib\site-packages\joblib\numpy_pickle.py", line 577, in _unpickle obj = unpickler.load() File "C:\Users\vanda\AppData\Local\Programs\Python\Python311\Lib\pickle.py", line 1213, in load dispatch[key[0]](self) File "D:\Django_MachineLearning_HealthcareApp-main\venv\Lib\site-packages\joblib\numpy_pickle.py", line 402, in load_build Unpickler.load_build(self) File "C:\Users\vang\AppData\Local\Programs\Python\Python311\Lib\pickle.py", line 1718, in load_build setstate(state) File "sklearn\tree\_tree.pyx", line 865, in sklearn.tree._tree.Tree.setstate <source code not available> File "sklearn\tree\_tree.pyx", line 1571, in sklearn.tree._tree._check_node_ndarray <source code not available> Exception Type: ValueError at /diagnose/liver/report Exception … -
Wagtail: include custom form in SnippetsViewSet
I'am trying to include a custom form in the SnippetsView of one of my models.The form's purpose is to let the user upload a csv-file to add Data, the model in question has a one-to-many relationship with a second model, which is then bulk-updated with the data from the csv-file. Th goal is that for very view of every instance of the model generated via the SnippetViewSet the form can be found and used in a seperate Tab created via TabbedInterface. I can of course add manually a form via @hooks.register in a SubMenuItem or I can just add a new FileField to my model and add a hook or overide the models's save method, so that if the user uploads a file in the wagtail-admin it will get used to update the second model. I'd like rather to know wether there is a simple way to add a custom form to a SnippetView without having to subclass wagtail.snippets.views.snippets.EditView and CreateView and creating a new template or at least one not involving to much ducktaping. Currently I can upload the model via csv in the django-admin. But I'd like that to be possible in wagtail-admin as well. -
ModuleNotFoundError: No module named 'captcha.fields'
By Executing command python manage.py runserver in vscode terminal occured this error : Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1073, in _bootstrap_inner self.run() File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1010, in run self._target(*self._args, **self._kwargs) File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 486, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ ...... File "<frozen importlib._bootstrap_external>", line 995, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "D:\<project path>\porsline\urls.py", line 10, in <module> path('', include('survey.urls')), ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\urls\conf.py", line 39, in include urlconf_module = import_module(urlconf_module) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\importlib\__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 995, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "D:\<project path>\survey\urls.py", line 2, in <module> from . import views File "D:\<project path>\survey\views.py", line 14, in <module> from . forms import CreateSurveyForm, CreateQuestionForm, ShowSurveyForm File "D:\<project path>\survey\forms.py", line 11, in <module> from captcha.fields import CaptchaField ModuleNotFoundError: No module named 'captcha.fields' …