Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pyQt5 ui connected a Django services
I want to create a program for organizations. that has a simple interface and is linked to the Django project for the large parent organization, Where you receive the order from one of the branches by to the interface ui ,, Django sends the results,, can I use puQt5 for ui interface and Django for server? Can I make a ui interface with pyQt5 for multy entreprises Connected to the django project with a mother entreprise? -
How can I create a user login/registration model using Django Rest Framework without getting a response code 403 when trying to create user?
So I am working on a project using Django and Django rest framework. I'm trying to create an api for my website which allows users to register/log in/log out. I'm following [this tutorial] (https://iheanyi.com/journal/user-registration-authentication-with-django-django-rest-framework-react-and-redux) for the initial set up. My issue is that when I try to run my test code to create a user, I get a response code 403 which I guess means I'm trying to do something I don't have permission to do? How can I get rid of this issue so I can create users? Here is my tests.py: from django.test import TestCase from django.urls import reverse from rest_framework.test import APITestCase from django.contrib.auth.models import User from rest_framework import status class TestUserApi(APITestCase): def setUp(self): self.test_user = User.objects.create_user('testuser', 'test@example.com', 'testpassword') self.create_url = reverse('user-create') def test_create_user(self): data = { 'username': 'foobar', 'email': 'foobar@example.com', 'password': 'somepassword' } response = self.client.post(self.create_url , data, format='json') # We want to make sure we have two users in the database.. self.assertEqual(User.objects.count(), 2) # And that we're returning a 201 created code. self.assertEqual(response.status_code, status.HTTP_201_CREATED) # Additionally, we want to return the username and email upon successful creation. self.assertEqual(response.data['username'], data['username']) self.assertEqual(response.data['email'], data['email']) self.assertFalse('password' in response.data) def test_create_user_with_short_password(self): data = { 'username': 'foobar', 'email': 'foobarbaz@example.com', 'password': 'foo' … -
How to access Product name and all details from sub Category using Django?
I want to get product name and all its details from sub category, I tried a lot to find how to do it but it didn't work When clicking on the sub category the related products should appear ,If anyone knows the query please tell me I have made four models First Main category Second category Third SubCategory Category contains the foregion key of the main category Also In sub category the foregion key of category is given And in the product model, the foreign key of the above three models is given I try this query Product.objects.all().select_related('main_category').select_related('category').select_related('sub_category') Please tell me and its html part too -
How to order the results by two columns using admin.display decorator
Please consider the following example: # models.py class Case(models.Model): number = models.SmallIntegerField(null=False, blank=False) year = models.SmallIntegerField(null=False, blank=False) ... #admin.py @admin.register(Case) class CaseAdmin(admin.ModelAdmin): list_display = ['case_number', ...] ordering = ['-year', '-number'] @admin.display(ordering=['-year', '-number']) def case_number(self, case): return f'{case.number} / {case.year}' Now how can I specify the order to be by '-year' and '-number' using the admin.display() decorator? If it can not be done with the admin.display() decorator, is there another way to achieve that? Thanks -
`django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured` when I try to start the daphne
I have a django project. When I start runserver - everything is fine. But if I try to start the daphne asynchronous server (daphne -p 8001 config.asgi:application), I get an error django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Settings in wsgi and asgi are the same os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') Maybe someone came across and can me help? Here ais full traceback File "/home/dima/PycharmProjects/TyuMeb/Back_reload/venv/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dima/PycharmProjects/TyuMeb/Back_reload/venv/lib/python3.11/site-packages/daphne/cli.py", line 171, in entrypoint cls().run(sys.argv[1:]) File "/home/dima/PycharmProjects/TyuMeb/Back_reload/venv/lib/python3.11/site-packages/daphne/cli.py", line 233, in run application = import_by_path(args.application) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dima/PycharmProjects/TyuMeb/Back_reload/venv/lib/python3.11/site-packages/daphne/utils.py", line 12, in import_by_path target = importlib.import_module(module_path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/dima/PycharmProjects/TyuMeb/Back_reload/config/asgi.py", line 16, in <module> from chat import routing File "/home/dima/PycharmProjects/TyuMeb/Back_reload/chat/routing.py", line 3, in <module> from . import consumers File "/home/dima/PycharmProjects/TyuMeb/Back_reload/chat/consumers.py", line 9, in <module> from chat.models import Conversation, Message File "/home/dima/PycharmProjects/TyuMeb/Back_reload/chat/models.py", line 3, in … -
Static url is not working whenever I am trying to use slug to show a blog details
My other pages static url is working great but when ever I am trying to show a blog details, my static url is changing its showing http://127.0.0.1:8000/blog/this-is-testing-number-1/media/assets/css/bootstrap.min.css instead of http://127.0.0.1:8000/media/assets/css/bootstrap.min.css my blog app views.py from django.shortcuts import render from .models import Blog # Create your views here. def details(request, slug): blog = Blog.objects.get(slug=slug) context = { 'blog':blog } return render(request, 'blog/blog_details.html', context) my blog app urls.py from django.urls import path, include from froala_editor import views from .views import * urlpatterns = [ path('froala_editor/',include('froala_editor.urls')), path('<slug>/', details, name='details') ] my blog details.html <!-- CSS ================================================== --> <link rel="stylesheet" href="media/assets/css/bootstrap.min.css" /> <link rel="stylesheet" href="media/assets/css/magnific-popup.css" /> <link rel="stylesheet" href="media/assets/css/owl.carousel.min.css" /> <link rel="stylesheet" href="media/assets/css/simple-scrollbar.css" /> <link rel="stylesheet" href="media/assets/css/fontawesome.all.min.css" /> <link rel="stylesheet" href="media/assets/css/style.css" /> <script src="media/assets/js/modernizr.min.js"></script> </head> my static settings STATIC_ROOT = 'staticfiles' STATIC_URL = '/static/' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') STATICFILES_DIR = { os.path.join(BASE_DIR , "public/static") } MEDIA_ROOT = os.path.join(BASE_DIR, 'public/static') MEDIA_URL = '/media/ my main urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('blog/', include('blog.urls')), path('account/', include('account.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += staticfiles_urlpatterns() how to fix this. I … -
issue sending uploaded image file from reactJS frontend to django python backend (file sending as undefined)
I am trying to send various data types from user input on the reactJS frontend to the Django python backend and getting an error where the text string sends but the image file does not. here is where I am sending the image and caption handleSubmit = async () => { try { const formData = new FormData(); console.log('Image: ', this.props.fileInput); console.log('Image type: ', typeof this.props.fileInput); console.log('Image is a File: ', this.props.fileInput instanceof File); formData.append('file', this.props.fileInput); // formData.append('file', this.props.file); formData.append('caption', this.state.caption); for (let pair of formData.entries()) { console.log(pair[0] + ', ' + pair[1]); } const response = await axios.post(API_URL, formData, { headers: { 'Content-Type': 'multipart/form-data' } }); if (response.status === 200) { console.log('Image uploaded successfully'); } } catch (error) { console.error(error); } } on the caption component and for the image component I did updateImage = async (imageId, caption) => { try { const formData = new FormData(); console.log('File:', this.state.file); console.log('Caption:', caption); formData.append('file', this.state.file); formData.append('caption', caption); for (let pair of formData.entries()) { console.log(pair[0] + ', ' + pair[1]); } const response = await axios.post(API_URL, formData, { headers: { 'Content-Type': 'multipart/form-data' } }); if (response.status === 200) { console.log('Image processed successfully'); const currentState = this.state; const newState = {...currentState}; newState.elements[imageId].URL = … -
Django formatting DecimalField to money
In my Django project I'm saving a money amount in a decimalField. The problem is the format of the number when I print it. I need it in the german money format 10.000,00 € so first a point as seperator and a comma for the cents. In Django I've only managed it to seperate everything with commas like 10,000,00 Has anyone an idea how I can implement it as I want? -
Ajax call to load dropdown with value associated with selected customer profile
Im getting a project that is associated with the selected customer. Whenever I try and submit the form im getting <ul class="errorlist"><li>project<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul>. For the life of me I can't figure why because its giving me the correct project. var querysetURL = "{% url 'administration:get_queryset' %}" $(document).ready(function () { $('#customer-profile').change(function (e) { e.preventDefault(); var customerProfile = $(this).find(":selected").val(); $.ajax({ url: querysetURL, method: 'GET', data: { filter_data: customerProfile }, success: function (data) { console.log(data); var projectDropdown = $('#id_project'); projectDropdown.empty(); var option = $('<option>').text(data); projectDropdown.append(option); }, error: function (xhr, status, error) { console.log("error"); console.log(error); console.log(status) } }); }); <div class="col-md-6" id="customer-profile"> {{ form.customer_profile|as_crispy_field }} </div> <!-- Display the project --> {{ form.project|as_crispy_field }} def get_queryset(request): filter_data = request.GET.get("filter_data") if filter_data: print("filtering..") profile = Profile.objects.get(id=filter_data) queryset = [profile.project] # queryset = Project.objects.filter(profile=profile) else: queryset = Project.objects.none() return HttpResponse(queryset) # TICKET CREATION VIEW @login_required def create_ticket(request): form = CreateTicketForm(data=request.POST or None, files=request.FILES or None) # queryset = get_queryset(request) if request.method == 'POST': if form.is_valid(): form_obj = form.save(commit=False) form_obj.created_by = request.user # project_id = request.POST.get('project') # print(project_id) # messages.info(request, project_id) # print(request.POST) # if project_id: # try: # project = Project.objects.get(id=project_id) # form_obj.project = … -
AttributeError: 'list' object has no attribute 'startswith' - Django views
from django.shortcuts import render Create your views here. def twitter(request): return render(request, 'index.html') def page2(request): cars = ['A', 'B', 'C', 'D'] context = {'cars': cars, 'result': 99} return render(request, 'page2.html', context) AttributeError: 'list' object has no attribute 'startswith' I don't get the startswith attr for list contained in my app -
How to create and change ownership of a directory from within a Docker container
I have a Django app with an api endpoint for creating a directory for a user. When receiving the request, the app runs subprocess.check_output to create a directory for the user in an NFS mount and then run chown so that only that user has the proper permissions to add files to the directory. Now, I'm trying to migrate the app to run inside a Docker container but need to retain this functionality. What is the best way to do this? I've thought of having a volume to the NFS mount in the host machine but I'm not sure if that works, specially since the user wouldn't exist inside the Docker container and hence chown would fail. Something else I thought was having a shell script which can be called from the Docker container and run in the host machine but I don't know if that's possible -
How can I create django application with VueJS like Inertia in Laravel?
I want to create a simple application with django, but I want use vuejs like Inertia in laravel. ¿What is the correct way to implement it? I don't want separate front and back. I need a great idea to implement it or examples. -
error on django application in heroku when debug is set to False
Please I wanted to test my django application on heroku with the team before buying the host, but I get server error(500) when I set debug=False and try to access the login page or signup page, I have gone through the code but not finding any issue, but when I set the debug=True, the login and signup pages open fine. Also, when I upload an image, it displays for a while, when I revisit the page, the image will disappear, please help. this is my setting.py """ Django settings for EtufuorFarm project. Generated by 'django-admin startproject' using Django 4.1.6. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ import datetime import os from pathlib import Path import dj_database_url import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY', 'django-insecure-qut(+bhgj@au6z4tl!_z8c(k%yes@)f(8x4lb%l6knh7n$d') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['etufuormarket.herokuapp.com'] # Application definition INSTALLED_APPS = [ #'admin_material.apps.AdminMaterialDashboardConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', … -
Tinymce doesn't generate pre-signed urls for uploaded images
I am developing a Django blog application where I utilize Tinymce as the text editor for the content of the posts. To store the uploaded images, I use AWS S3. The problem is that Tinymce does not generate pre-signed URLs for the uploaded images, leading to access denied errors when the expiration time is reached. This is the error I get: AccessDenied Request has expired 3600 2023-06-07T03:26:09Z 2023-06-07T15:46:49Z xxxxxxxxx xxxxxxxxx When an image is uploaded through Tinymce, it is stored as a link in the text area. However, Tinymce does not generate new pre-signed URLs for the images when a post is opened, resulting in the images retaining the same URL that was initially generated during the post's save operation. Since the pre-signed URLs for the Tinymce images do not change, when the expiration time set for the URLs is reached, the images become inaccessible, and I encounter an "access denied" error. I have other images in the blog that are served fine. The problem is just happening with those uploaded in Tinymce These are some relevant code snippets: uploadfile.js const image_upload_handler_callback = (blobInfo, success, failure, progress) => { const xhr = new XMLHttpRequest(); xhr.withCredentials = false; xhr.open('POST', '/' + … -
Design pattern for Yelp-like app using microservices
I'm a newbie in microservices so forgive me if my question sounds a little naive. I'm designing a Yelp-like app for gyms. in this application, users can create a gym and its related data, and others can review or rate it. My question is how to design its services in microservice architecture? Is it a good design pattern to create these three services? Auth service that has a user table and manage user related data for login and registeration. Gym service for gym CRUD operation such as posting a gym, updating it, and so on. User service for relating gyms to their owners through event-driven architecture and message broker like Kafka. it also manage user profile data, such as resetting the password or changing the username, email, first name and last name. If this approach is reasonable, I want to know how does the relationship between user and auth service works. do I need to keep all the user data in the auth service and fetch or update it through published events, or should I duplicate the user data in a new user table in the user service database? -
Filter nested Django objects in serializer
In an application I am working on I would like to filter the objects returned by a serializer based on the user's is_staff status. If a user has is_staff = True I would like for all of the nested Book objects to be returned. If the user's is_staff status is False I would like for only Books with active = True. How can I achieve this using this viewset: class BookCategoryViewSet(viewsets.ReadOnlyModelViewSet): """ View available books by category """ queryset = BookCategory.objects.all() serializer_class = BookCategorySerializer and these serializers: class BookSerializer(serializers.ModelSerializer): """ Serialize Book for list endpoint """ class Meta: model = Book fields = ( 'id', 'name', 'description', 'category', 'category_name', 'thumbnail', 'active', ) class BookCategorySerializer(serializers.ModelSerializer): """ Serialize books by category """ books = BookSerializer(many=True, read_only=True, source='book_set') class Meta: model = BookCategory fields = ( 'name', 'active', 'books', ) NOTE: I am trying to filter the Books not the BookCategories based on the user status. -
Unable to connect to redis from celery
I'm using the django application where i want to run celery workers. But when i hit python -m celery -A cartpe worker, i get the following error consumer: Cannot connect to redis://redis:6379/0: Error 8 connecting to redis:6379. nodename nor servname provided, or not known.. This is my celery.py file import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cartpe.settings') app = Celery('cartpe') # Load the celery configuration from Django settings. app.config_from_object('django.conf:settings', namespace='CELERY') # Discover asynchronous tasks in Django app modules. app.autodiscover_tasks() __init__.py from .celery import app as celery_app __all__ = ('celery_app',) settings.py # Celery settings CELERY_BROKER_URL = 'redis://redis:6379/0' # initially had 'redis://localhost:6379/0' which didn't work either CELERY_RESULT_BACKEND = 'redis://redis:6379/0' I have redis running in docker. Is this the reason i'm unable to connect to redis ? Also i'm using MacOs. I saw a number of solutions related to this but none worked. What can i do here to resolve the issue ? -
Is it possible to return a Django.model instance with htmx?
I'm using django with django-htmx. I want to use hx-vals to return an instance that was given by the context to the django template. {% for auszubildender in auszubildende %} <div hx-post="/htmxFunctions/azubiAnzeigen" hx-trigger="click" hx-target="#content" hx-vals='{ "test": "test", "auszubildender": "{{auszubildender}}"}'> {% if auszubildender.first_name %} [...] {% endif %} </div> {% endfor %} When I'm accesing auszubildender with request.POST.get("auszubildender") it returns a str (the username as auszubildender is a django default Usermodel). Is there a way to post / get the instance or will a POST method always return just a string? In this case I will just use the PK to access the instance. -
Authentication for grafana behind a reverse niginx proxy
I am running a react app with a django backend. Users can log in to my app via django and are redirected to my react app. Now I want to show a grafana panel. I already set up a self-hosted grafana instance with a reverse proxy (for https). I can embedd the panel without a problem (iframe) when I use grafanas anonymous_authentication. But this is not an option for me. Also not an option for me is a login page on in app/iframe. I am reading alot that there is the option to manage the authentication via the reverse proxy. But since I am a nginx noob, I don't really know how I can implement this. Can someone guide me here? I think I have to somehow log in via the proxy to grafana My nginx setup thus far: server { server_name myserver.co; location / { proxy_set_header Host $http_host; proxy_pass http://localhost:3000/; } ##here is also some cert stuff } server { if ($host = myserver.co) { return 301 https://$host$request_uri; } listen 80; listen [::]:80; server_name myserver.co; return 404; } -
I'm getting "This field is required" from my Django Form when using Client().post to test even thought form.data shows values in those fields
I'm trying to test some form logic in my views.py and need to simply pass a form to that view in order to do that but I can't figure out why it isn't receiving a valid form when passed using a Client().post from my tests. When using the form from the browser normally it works fine. I'm using Django test Client submitting a form with a POST request and How should I write tests for Forms in Django? as guidance with no luck after looking at many different resources. The errors from form.errors shows name - This field is required address - This field is required However my form.data shows <QueryDict: {"'name': 'foo bar', 'address': '2344 foo st'}": ['']}> The working live form has the form.data as: <QueryDict: {'csrfmiddlewaretoken': ['htR...Rel', 'htR...Rel'], 'name': ['test'], 'address': ['test'],'submit': ['Submit_Form']}> I've played around with getting a "csrfmiddlewaretoken" but I don't feel like that the problem. I've also tried setting the .initial and played around with content type. Is the form.data not what is looked at? form.is_valid() is True before the post to the view.py. Thanks in advance for the help! My tests code is: @pytest.mark.django_db def test_add_bar_with_logged_in_user_form(setUpUser, django_user_model): from ..models.forms import BarForm from django.test … -
Django join through table even if don't match
I'm starting to use Django, but I'm just a beginner. I have a problem with Django Queries, and although I've done a lot of research online, I haven't found any answers that can help me. Models.py: class Articles(models.Model): ID = models.AutoField(primary_key=True) description = models.TextField() price = MoneyField(blank=True, null=True, decimal_places=2, max_digits=8, default_currency='EUR') class Meta: ordering = ('description',) def __str__(self): return self.description class Interventions(models.Model): ID = models.AutoField(primary_key=True) start_date = models.DateField() description = models.TextField() Item_ID = models.ManyToManyField(Items, through="Detail", blank=True) class Detail(models.Model): ID = models.AutoField(primary_key=True) article_id = models.ForeignKey(articles, on_delete = models.CASCADE) Intervention_ID = models.ForeignKey(Interventions, on_delete = models.CASCADE) quantity = models.IntegerField(null=True, blank=True, default='1') I would like to be able to create a Query that takes all the records of the 'Interventions' model and all the records of the 'Details' table. The problem is that if an intervention is made, but without having used any article, the intervention itself is not displayed. How can I do? I tried with prefetch_related but it doesn't seem to work. Heartfelt thanks to everyone. -
Sonarqube displaying 0% of coverage and no unittest in django project using coverage.py
I'm working on creating unitest for a django project I installed sonarqube : docker run -d --name sonarqube -e SONAR_ES_BOOTSTRAP_CHECKS_DISABLE=true -p 9000:9000 sonarqube:latest through docker image and sonar-scanner using this command : docker run -v /home/hind/Desktop/map-manager:/usr/src --network="host" sonarsource/sonar-scanner-cli -Dsonar.host.url=http://localhost:9000/ -Dsonar.login=sqp_e7171bd635104a04d29c523243cf54000946ea7f and I before that I added coverage to my project , I created 23 unitest and all running well except for one that is failling I run tests with : coverage run manage.py run test maps and when I run the report of the sonarqube resultcoverage report and the report is displaying this : Name Stmts Miss Cover --------------------------------------------------- app/__init__.py 0 0 100% app/settings.py 58 10 83% app/urls.py 12 0 100% manage.py 13 6 54% maps/__init__.py 0 0 100% maps/admin.py 141 62 56% maps/migrations/__init__.py 0 0 100% maps/models.py 163 10 94% maps/templatetags/__init__.py 0 0 100% maps/tests.py 195 3 98% --------------------------------------------------- TOTAL 582 91 84% but in sonar-scanner I get 0.0% coverage and nothing in unitest enter image description here sonarsube result I dont know what's the problem so the coverage is not 0.0% -
How to allow multiple IP addresses and use that ip address from different network in django?
Therefore, I need to access my Django project from localhost to some other different network with a different different domain or IP address (my custom domain and ip address). Is there a method to achieve without using any live domain like AWS or GoDaddy? The Django host, ngrok, serveo, and thord parts I tried did not provide a custom domain name or IP. -
Django Machina - display post times in local timezone
I am using django-machina as a forum. I want post times in the forums to be displayed to users in their local times. I have TIME_ZONE = 'UTC' and USE_TZ = True in my settings.py file. I have also installed "pytz." The times are currently displayed in UTC time. I have attempted to use the following in a template: <small>{{ node.last_post.created | localtime }}</small> However this has no effect on the display times. I put this in the template as a test: {% get_current_timezone as TIME_ZONE %} {{ TIME_ZONE }} and it displays "UTC" How can I get the times to display in the user's local time zone? -
Error in AES Encryption/Decryption via python
We have integrated a API through which I am getting a encrypted data. Now in the docs they have given me a software link to decrypt the data. Here is the website they have recommend me to use to decrypt the received data: https://aesencryption.net/ It works fine and I am getting the decrypted data on this website On this website they have given their code they are using for decryption & that is in PHP. I have used chat GPT to convert that PHP code in python with little modification of my own. But it doesn't work with this code. I am mentioning everything that I have and have tried. import hashlib from Crypto.Cipher import AES import base64 class AESFunction: secret_key = None key = None decrypted_string = None encrypted_string = None @staticmethod def set_key(my_key): key = bytes.fromhex(my_key) sha = hashlib.sha256() sha.update(key) key = sha.digest()[:32] AESFunction.secret_key = AESFunction.key = key @staticmethod def get_decrypted_string(): return AESFunction.decrypted_string @staticmethod def set_decrypted_string(decrypted_string): AESFunction.decrypted_string = decrypted_string @staticmethod def get_encrypted_string(): return AESFunction.encrypted_string @staticmethod def set_encrypted_string(encrypted_string): AESFunction.encrypted_string = encrypted_string @staticmethod def encrypt(str_to_encrypt): cipher = AES.new(AESFunction.secret_key, AES.MODE_CBC) encrypted_bytes = cipher.encrypt(AESFunction.pad(str_to_encrypt).encode('utf-8')) AESFunction.set_encrypted_string(base64.b64encode(encrypted_bytes).decode('utf-8')) @staticmethod def decrypt(str_to_decrypt): cipher = AES.new(AESFunction.secret_key, AES.MODE_CBC) decrypted_bytes = cipher.decrypt(base64.b64decode(str_to_decrypt)) AESFunction.set_decrypted_string(AESFunction.unpad(decrypted_bytes).decode('utf-8', errors='replace')) @staticmethod def pad(text): block_size = …