Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
bring the customer id from auto search box and then redirect to it the customer update page
I have a Django project. it has the functionality to create a customer and its working fine.I have added the auto search box in the same template to search already created customer. when i enter word its suggesting the names already saved in the database. but when i clicked a name its **displaying in the search box as [object object] not the correct name **. and I created button to selected customer to update . but when i clicked the button its saying "Please select a customer from the autocomplete list" i need to find whats the problem in my code. I need to correctly show the selected result from auto suggest search box and when i clicked the update button it should redirect to the customer update page. here is the html code of my auto complete search box" `<div class="col-md-6 mx-auto"> <div id="autocomplete" class="autocomplete"> <input class="autocomplete-input" /> <ul class="autocomplete-result-list"></ul> </div> <button id="update-customer-button" type="button" onclick="redirectToUpdateCustomer()">Update</button> </div> </div>"` and here is my JavaScript for the auto complete search and redirecting to the update page" `const selectedCustomerId = null; // Existing Autocomplete setup new Autocomplete('#autocomplete', { search: input => { console.log(input); const url = `/master/get_customers/?search=${input}`; return new Promise(resolve => { fetch(url) … -
while activating virtual environment in python showing this
ps1 cannot be loaded because running scripts is disabled on this system. run this command "Set-ExecutionPolicy RemoteSigned" then showing this To change the execution policy for the default (LocalMachine) scope, start Windows PowerShell with the "Run as administrator" option. To change the execution policy for the current user, run "Set-ExecutionPolicy -Scope CurrentUser" -
"TypeError: unsupported operand type(s) for /: 'str' and 'int'" when dividing fields from Django model
I am trying to calculate how much progress a user has made towards their monetary goal they set inside a Django model, but it keeps giving me this error: TypeError: unsupported operand type(s) for /: 'str' and 'int' This is how I'm trying to calculate the user's progress: def calculateGoalPercentage(self): onePercent = self.goal / 100 goalPercentage = self.calculateBalance() / onePercent return goalPercentage This is my model: class Space(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30, default="New Space") balance = models.FloatField(default=0.00) goal = models.FloatField(default=100.00, validators=[MinValueValidator(1.00)]) typeChoices = [ (0, "Private"), (1, "Shared"), ] space_type = models.CharField(max_length=7, choices=typeChoices, null=True, blank=True) owner = models.ForeignKey(to=User, on_delete=models.CASCADE, blank=True, null=True) created = models.DateField(auto_now=True) records = models.ManyToManyField(Record, blank=True, default=None) notes = models.TextField(default="") def calculateBalance(self): total = 0 for record in self.records.all(): total += record.amount return total def calculateGoalPercentage(self): onePercent = self.goal / 100 goalPercentage = self.calculateBalance() / onePercent return goalPercentage def __str__(self): return self.name Does anyone know what's going on? This seems like an error I would find back when I was a beginner, so I think I'm missing a small detail. -
Django - Not Migrating
I just made a new app called Recipes as I am new to Django and writing a test project and I came across this error when I made a model called Recipes and imported to admin.py I would like suggestions and code snippets please. Traceback (most recent call last): File "/home/thelordthemythxwz/CodesAtom/TheLearning/manage.py", line 22, in <module> main() File "/home/thelordthemythxwz/CodesAtom/TheLearning/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/thelordthemythxwz/.local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/thelordthemythxwz/.local/lib/python3.10/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/home/thelordthemythxwz/.local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/thelordthemythxwz/.local/lib/python3.10/site-packages/django/apps/registry.py", line 124, in populate app_config.ready() File "/home/thelordthemythxwz/.local/lib/python3.10/site-packages/django/contrib/admin/apps.py", line 27, in ready self.module.autodiscover() File "/home/thelordthemythxwz/.local/lib/python3.10/site-packages/django/contrib/admin/__init__.py", line 50, in autodiscover autodiscover_modules("admin", register_to=site) File "/home/thelordthemythxwz/.local/lib/python3.10/site-packages/django/utils/module_loading.py", line 58, in autodiscover_modules import_module("%s.%s" % (app_config.name, module_to_search)) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/thelordthemythxwz/CodesAtom/TheLearning/Recipes/admin.py", line 6, in <module> admin.site.register(Recipes) File "/home/thelordthemythxwz/.local/lib/python3.10/site-packages/django/contrib/admin/sites.py", line 117, in register for model in model_or_iterable: TypeError: 'type' object is not iterable -
How to localize django-filter labels using django-parler
I am developing an e-commerce website and I am using django-filter to filter products by size, category, color, price. However I can't find a way to translate labels for filters using django-parler, I managed to translate choices for ascending and descending values but I am stuck here. Here is my filters.py lass ProductFilter(django_filters.FilterSet): CHOICES = ( ('ascending', _('Ascending')), ('descending', _('Descending')) ) price = django_filters.RangeFilter( widget=django_filters.widgets.RangeWidget(attrs={"class":"price-search"})) ordering = django_filters.ChoiceFilter(label='Sort', choices = CHOICES, method='filter_by_order') class Meta: model = Product fields = ['size', 'color', 'category'] def filter_by_order(self, queryset, name, value): expression = 'price' if value == 'ascending' else '-price' return queryset.order_by(expression) also HTML: <section class="category-products"> <div class="container"> <div class="category-wrapper"> {% for product in filtered_products %} <div class="category-item-block"> <div class="category-item"> <div class="category-item-image"> <div class="img-wrapper"> <a href="{% url 'product' product.slug %}"><img src=" {{product.thumbnail.url}}" alt="" /></a> </div> <h2>{{product.name}}</h2> </div> <div class="category-item-info"> <p>{{product.short_description}}</p> </div> <div class="category-item-price"> <p class="price">{{product.price}} AMD</p> <p class="price-monthly">{{product.price_monthly}} AMD / {% trans "monthly" %}</p> </div> <div class="buy"> <a href="{% url 'buy' product.id %}" class="buy-now"> <p>{% trans "Buy Now" %}</p> </a> <div class="add-cart"> <div class="img-wrapper"> <button hx-get="{% url 'add_to_cart' product.id %}" hx-target="#menu-cart-button" hx-swap="outerHTML" > <img class="cart-catalog" src="{% static 'img\add-to-cart.svg' %}" alt="" /> </button> </div> </div> </div> </div> </div> {% endfor %} <div class="load-more"> <button> {% … -
How to practice django projects
I am a beginner in django I have completedudemy courses. I have a basic knowledge about django and I don't know how now practice . Any youtube channel or other resources . Any other suggestions I am completed udemy course but now I don't know what to do now -
Django does not append trailing slash automatically
I'm creating a website using Django==4.2.3, the problem I'm facing is when I visit a URL for example http://127.0.0.1:8000/calculators it sends me to http://127.0.0.1:8000/calculators/ (it appends slash in the end as it should. However in the production server it doesn't append the slash to URL. For example https://example.com/calculators throws a 404 instead of redirecting to https://example.com/calculators/' I did not use the APPEND_SLASH setting as I think that's already true by default. Here is how my middleware looks like: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "whitenoise.middleware.WhiteNoiseMiddleware", "django_browser_reload.middleware.BrowserReloadMiddleware", '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', ] Here is how I registered the URLs: calculators/urls.py from django.urls import path from .views import * urlpatterns = [ path('', CalculatorsView.as_view(), name='calculators'), path('stripe-fee/', StripeFeeCalculator.as_view(), name='stripe_fee_calculator'), path('fiverr-fee/', FiverrFeeCalculator.as_view(), name='fiverr_fee_calculator'), ] project/urls.py urlpatterns = [ ... path('calculators/', include('calculators.urls')), ... ] Please help me figure out how to solve this problem, thanks in advance! -
If I encode a JWT and send it in a URL then surely I need the secret key to decode it?
I have this function to encode a JWT token that I send in the URL so an application. encoded_token = jwt.encode({'token': token}, os.environ['SECRET_KEY'], algorithm='HS256') On the application side I decode the key and then use it to get the credentials of a user. Surely if I encode a JWT token using the above function and my secret key, do I need that secret key to decode it on the application side? At the moment that is not the case and the following function on the application side decodes the key and it's correct because I get the credentials of the user associated with the said token. So this is a security risk because I send the token in the URL (cannot seem to find another way)? function decodeJwt(token) { var base64Payload = token.split(".")[1]; var payload = decodeURIComponent( atob(base64Payload) .split("") .map(function (c) { return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2); }) .join("") ); return JSON.parse(payload); } Can someone please tell me why my token is decoded without my secret key and also maybe give me another way I can send the token to the application. Help is appreciated -
Django Foreign Key. How to access child model through the parent
So I created custom Profile model for a user and it's connected to the base Django User model via Foreign Key. I can easily access User model's fields through my Profile model because the Profile model has the field with Foreign Key to a User model (for example profile.user.username and etc.) But how do I access Profile model fields via User model? Here is the Profile Model user = models.ForeignKey(User, on_delete=models.CASCADE) id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True) username = models.CharField(max_length=150) email = models.EmailField() image = models.ImageField(upload_to='images/user_profiles', blank=True, null=True) def __str__(self): return f"{self.user}'s profile" And I've tried to access profile id like that, but it doesn't work a href="{% url 'profile' pk=request.user_profile.id %}" ...``` path('profile/<str:pk>/', views.user_profile_view, name='profile'), -
requests.user returns AnonymousUser when used in api view other than login
I am using Django's default authentication and authorization system. I have used DRF in backend and React in frontend #views.py from rest_framework.decorators import api_view from rest_framework.response import Response from django.contrib.auth.models import User from django.contrib.auth import authenticate,login from .models import * from .serializers import * import json # Create your views here. @api_view(['GET']) def slips(requests): if requests.method == 'GET': data = slip.objects.all() serializer = slipserializer(data,many = True) return Response(serializer.data) @api_view(['GET']) def packages(requests): if requests.method == 'GET': data = package.objects.all() serializer = packageserializer(data,many = True) return Response(serializer.data) @api_view(['POST']) def register(requests): if requests.method == 'POST': try: data = requests.body.decode('utf-8') ref_data = json.loads(data) usr = User.objects.create_user(ref_data['firstname'],ref_data['email'],ref_data['password']) usr.last_name = ref_data['lastname'] usr.save() login(requests,usr) return Response({'message':'registered successfully'}) except: return Response({'message':'something went wrong'}) @api_view(['POST']) def logIn(requests): if requests.method == 'POST': try: data = requests.body.decode('utf-8') ref_data = json.loads(data) uname = User.objects.get(email = ref_data['ID']) usr = authenticate(username = uname,password = ref_data['password']) login(requests,usr) return Response({'message': 'successfully logged in'}) except: print('failed') return Response({'message': 'something went wrong'}) @api_view(['GET']) def projects(requests): if requests.method == 'GET': proj = project.objects.all() serializer = projectserializer(proj,many = True) return Response(serializer.data) @api_view(['GET']) def skills(requests): if requests.method == 'GET': sk = skill.objects.all() serializer = skillserializer(sk,many = True) return Response(serializer.data) @api_view(['GET']) def tech(requests): if requests.method == 'GET': tech = technology.objects.all() serializer = … -
Upload Gigabytes of files to Storage Account from Django
I have a project setup with Django and ReactJs. The use case is, users will upload Gigabytes of files and those are to be stored to their respective folders in Azure Storage Account File Shares service (using Azure Python SDK). How do I upload them through backend (Django)? How can it be handled in the scalability perspective as well? I came across RabbitMQ and Kafka to redirect the upload through backend, but since it is not yet implemented. I'm looking for suggestions and other possible ways to do the same. Any suggestions to the scenario would be helpful. Thank you! -
Problem with rendering post host profile picture in DJango template
I am trying to render a Django template with different post made by several users. In each individual post, I want to display the profile picture of the person whom created the post. For some reason, the template renders with the posts in full display but without the profile picture. I have tried to display profile pictures using absolut URL and it works fine, but it does not work dynamically when I try to access the profile picture in the database. Also, I have made sure that there are profile pictures in the database by uploading pictures from the admin panel. Here are my codes. Model: class Member(PermissionsMixin, AbstractBaseUser): # Fields for sign up page username = models.CharField( _("Användarnamn"), max_length=50, unique=True, default='') email = models.EmailField( _("Mail"), max_length=100, unique=True, default='') age = models.PositiveIntegerField(_("Ålder"), null=True, blank=False) country = models.CharField(_("Land"), max_length=50, null=True, blank=True) county = models.CharField(_("Län"), max_length=50, null=True, blank=True) city = models.CharField(_("Stad"), max_length=50, null=True, blank=True) sex = models.CharField(_("Kön"), max_length=50, null=True, blank=True, choices=sex_choices) avatar = models.ImageField( _("Profilbild"), upload_to="static/user_profile_pics", null=True, blank=True) account_created = models.DateTimeField( _("Medlem sedan"), null=True, auto_created=True) last_login = models.DateTimeField( _("Senast inloggad"), null=True, auto_created=True) city_name = models.CharField(max_length=100, null=True, blank=True) country_name = models.CharField(max_length=100, null=True, blank=True) objects = CustomUserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = [] is_staff … -
Django - Celery - missing required positional argument - 'NoneType' object has no attribute 'delay'
When I define a task with parameters, I get the error: missing 1 required positional argument Which, I'm not if it really is missing one. I am passing the argument in delay in views.py. I tried defining the task without any arguments and it says: NoneType' object has no attribute 'delay' Besides, when I run a celery worker, it recognizes the task: [tasks] . posts.tasks.say_hello_task Why is this happening? celery.py: from celery import Celery import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "zwitter.settings") app = Celery("zwitter") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() settings.py: from datetime import timedelta CELERY_ACCEPT_CONTENT = ["json"] CELERY_RESULT_ACCEPT_CONTENT = ["json"] CELERY_TASK_SERIALIZER = "json" CELERY_RESULT_SERIALIZER = "json" CELERY_TASK_ALWAYS_EAGER = False CELERY_RESULT_BACKEND = "rpc://" CELERY_BROKER_URL = "amqp://" CELERY_RESULT_EXPIRES = timedelta(days=1) CELERY_WORKER_PREFETCH_MULTIPLIER = 1 tasks.py: @shared_task def say_hello_task(name): print(f"hello {name}") views.py: tasks.say_hello_task().delay("john") It says -
Want to log in on the Django side and also be logged in on the Vue side
I have a Django app with some pages and then I use Django Rest Framework to supply data to a Vue application, including loggin the user in. The Django website and the Vue application are not on the same domain or server or country or universe for that matter. I want to know how can I make it that if I log in on the Django side and I am redirected to the Vue app that I am also logged in on the Vue side? And visa versa if I log in on the Vue side that I am also logged in on the Django side. I am using JWT authentication and I thought about sending the token to the page (Django side if logged in on Vue side) I go to after being logged in but this seems to be impossible to do, or I just cannot find an answer of how to do it. -
AES encryption/decryption issue with RSA-encrypted key and IV in Python
'''import base64 import os import json import requests from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.backends import default_backend from cryptography.x509 import load_pem_x509_certificate import requests import json from cryptography.hazmat.primitives.ciphers import Cipher, algorithms from cryptography.hazmat.primitives.ciphers.aead import AESGCM import secrets import binascii def aes_gcm_encrypt(key, iv, plaintext, authenticated_data): aesgcm = AESGCM(key) ciphertext = aesgcm.encrypt(iv, plaintext, authenticated_data) return ciphertext def aes_gcm_decrypt(key, iv, ciphertext, authenticated_data): aesgcm = AESGCM(key) plaintext = aesgcm.decrypt(iv, ciphertext, authenticated_data) return plaintext ivs = "abcdefghijklmnop" keys = "abcdefghijklmnopqrstuvwxyzabcdef" iv_bytes = ivs.encode('utf-8') key_bytes = keys.encode('utf-8') print("len of bytes: ",len(iv_bytes),len(key_bytes)) plaintext = b'This is going to encrypt' authenticated_data = b'Additional data for authentication' ciphertext = aes_gcm_encrypt(key_bytes, iv_bytes, plaintext, authenticated_data) ciphertext_hex = binascii.hexlify(ciphertext).decode('utf-8') decrypted_text = aes_gcm_decrypt(key_bytes, iv_bytes, ciphertext, authenticated_data) """print(f"Ciphertext: {ciphertext}") print(f"Ciphertext hex: {ciphertext_hex}") print(f"Decrypted text: {decrypted_text}")""" def encrypt_data(iv,key, certificate): encoded = "" encrypted = None try: # Load the certificate cert = load_pem_x509_certificate(certificate.encode(), default_backend()) # Extract the public key public_key = cert.public_key() # Encrypt the data encrypted = public_key.encrypt( iv, padding.PKCS1v15() ) encrypted1 = public_key.encrypt( key, padding.PKCS1v15() ) # Base64-encode the encrypted data encoded = base64.b64encode(encrypted).decode() encoded1 = base64.b64encode(encrypted1).decode() except Exception as e: print(e) return encoded.replace("\\r", "").replace("\\n", ""),encoded1.replace("\\r", "").replace("\\n", "") AES encryption print("AES … -
Custom third party API authentication and restful services using django
I am basically pretty new in django and learning. I have started learning making APIs and authentications and stuffs like that. But I need some guidance. So, basically I am supposed to use some third party APIs for logging in which will provide me with the bearer auth token. And by using that token I am supposed to use the other APIs of the provider. If someone can guide me towards some proper tutorial or post which could help me that would be great. Tried using Django Rest Framework but most of them are for creating new APIs but not for consuming any third party API. -
User doesn't exist problem in login page of django User model
I have created one simple recipe website. In which i am creating a login page and register page. The register page is working fine and it saving the user credential into the User model. but when i have created the login page. it showing that username doesn't exist but the user is registered with same username and password. I have tried all the query like using filter and get separately..but didn't get any desired result. I expect that when user type their user name and password it redirect to recipe page. if the credentials are wrong it redirect to login page def login_page(request): if request.method == "POST": username = request.POST['username'] print(username) password = request.POST['password'] # print(User.objects.filter(username=username)) user = authenticate(username = username, password = password) if user is None: messages.info(request, "user do not exit. please REGISTER") return redirect('/user_login/') else: login(request, user) return redirect('/receipes/') return render(request, 'login_page.html') def register_page(request): try: if request.method == "POST": username = request.POST['username'], first_name = request.POST['first_name'], last_name = request.POST['last_name'] if User.objects.filter(username=username): messages.info( request, "Username already exist! Please try some other username.") return redirect('/user_register/') user = User.objects.create( username=username, first_name=first_name, last_name=last_name ) user.set_password(request.POST['password']) user.save() messages.success( request, "Your Account has been created succesfully!!") return redirect('/user_register/') except: pass return render(request, 'register_page.html') -
Django- How can I add sizes for my product?
I created my models but now I don't know how to create a form with all the sizes I added for every product to add it to detail view. can you please help me, Thanks. here is my models.py. from django.db import models from django.shortcuts import reverse class Size(models.Model): size = models.CharField(max_length=250) def __str__(self): return self.size class Product(models.Model): title = models.CharField(max_length=150) description = models.TextField() price = models.PositiveIntegerField() image = models.ImageField(upload_to='product/product_cover', blank=False) active = models.BooleanField(default=True) sizes = models.ManyToManyField(Size, through='ProductSize') datetime_created = models.DateTimeField(auto_now_add=True) datetime_modified = models.DateTimeField(auto_now=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('product_detail', args=[self.id]) class ProductSize(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) size = models.ForeignKey(Size, on_delete=models.CASCADE) count = models.IntegerField(default=1) def __str__(self): return self.product -
how installing chained foreignkey
django.db.utils.OperationalError: (1045, "Access denied for user '91815'@'localhost' (using password: YES)") ERROR: Could not find a version that satisfies the requirement django-chained-foreignkey (from versions: none) ERROR: No matching distribution found for django-chained-foreignkey -
Hi,How can I add a photo to a web page with Django?
how can I create this feature so that the user can choose a photo for a product from within the system or enter its URL? This image should be added to the product list along with other information. This is my code. The page loads, but it doesn't do anything special and it doesn't have the URL box either. {% extends "auctions/layout.html" %} {% block body %} <h2 id="h2">Create List</h2> <form method="POST"> {% csrf_token %} <h3 id="h3">Title:</h3> <input id="input" placeholder="Title" type="text" name="createlist_title"/> <h3 id="h3">Category:</h3> <input id="input" placeholder="Category" type="text" name="category"/> <h3 id="h3">Description:</h3> <textarea id="input" placeholder="Description" type="text" name="createlist_description"> </textarea> <h3 id="h3">Firstprice:</h3> <input id="input" placeholder="first_price" type="number" name="createlist_price"/> <form action="upload.php" method="post" enctype="multipart/form-data"> <h3 id="h3"> Upload image:</h3> <input id="input" type="file" id="fileUpload" name="fileUpload"> <input id="button2" type="submit" value="upload"> </form>`` <form method="post" enctype="multipart/form-data" action="{%url "upload_image" %}"> <h3 id="h3"> Upload image with URL:</h3> {% csrf_token %} {{ form.as_p }} <button id="button2" type="submit">Upload</button> </form> <button id="button" class="btn btn-outline-primary" type="submit">Submit</button> </form> -
Why is Heroku unable to find my "manage.py" file in the Django app I'm trying to deploy?
When I deploy my Django app on Heroku I get this: As you can see it says that there is a dyno running and then when I enter "heroku ps" it says that no dynos are running. "herokeroku ps eroku ps" is just a glitch in the CLI. I checked the logs and it said that the deployment failed and in the release logs of that deployment it says it can't find the "manage.py" file. However, the "manage.py" file is there in the root folder and the Heroku branch is up to date. I can run the app locally with "heroku local". Do you know why Heroku might not be able to find a "manage.py" file? Thank you -
Implementing Secure Data Encryption and Decryption between Frontend and Backend using Public and Private Keys
Front end will invoke some API which will provide Public key: Using that public key front end should encrypt it Use the API(POST/PUT) to send the data back. Back end API will decrypt the data using private and public key and store the content. When the same data is retrieved at front end: Generate the keys and encrypt the data using public key Decrypt the data at front end using the private and public key. what heading can i give for this question I have three fields which needed to be encrypted and decrypted but I'm only able to encrypt its not decrypting .can u help how to decrypt? myapp/utils.py from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP import base64 def encrypt_data(data, public_key_path): with open(public_key_path, 'rb') as f: public_key = RSA.import_key(f.read()) cipher_rsa = PKCS1_OAEP.new(public_key) encrypted_data = cipher_rsa.encrypt(data.encode('utf-8')) return base64.b64encode(encrypted_data).decode('utf-8') def decrypt_data(encrypted_data, private_key_path): encrypted_data = base64.b64decode(encrypted_data) with open(private_key_path, 'rb') as f: private_key = RSA.import_key(f.read()) cipher_rsa = PKCS1_OAEP.new(private_key) decrypted_data = cipher_rsa.decrypt(encrypted_data) return decrypted_data.decode('utf-8') myapp/views.py def add_candidate(request): if request.method == 'POST': form = CandidateForm(request.POST) if form.is_valid(): candidate = form.save(commit=False) # Encrypt sensitive fields using the public key candidate.adharnumber = encrypt_data(candidate.adharnumber, settings.PUBLIC_KEY_PATH) candidate.pannumber = encrypt_data(candidate.pannumber, settings.PUBLIC_KEY_PATH) candidate.passportnumber = encrypt_data(candidate.passportnumber, settings.PUBLIC_KEY_PATH) candidate.save() return redirect('candidate_list') else: … -
Javascript integration with django template problem
In my django project when i write show password script within login.html file it works fine but when i place the script in static directory of my project it will effect email and password1 field not password1 and password2 field. {% load static %} {% load widget_tweaks %} {% load socialaccount %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="{% static 'Notes/signup.css' %}" /> <!--Font Awesome Link--> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <title>Signup Page</title> </head> <style> .errors label{ font-size: 11px; color: red; position: relative; bottom: 9px; } </style> <body> <div class="container"> <form id="login" method="post"> {% csrf_token %} <h1>Signup</h1> {% render_field form.username type="text" placeholder="Username" %} {% if messages %} {% for message in messages %} {% if message.tags == "username error" %} <div class="errors"> <label><i class="fa-sharp fa-solid fa-circle-exclamation"></i>{{message}}</label> </div> {% endif %} {% endfor %} {% endif %} {% render_field form.email type="email" placeholder="Email" %} {% if messages %} {% for message in messages %} {% if message.tags == "email error" %} <div class="errors"> <label><i class="fa-sharp fa-solid fa-circle-exclamation"></i>{{message}}</label> </div> {% endif %} {% endfor %} {% endif %} {% render_field form.password1 type="password" placeholder="Password" %} {% render_field form.password2 type="password" placeholder="Confirm Password" %} {% … -
No Audio Detected Assembly API
I'm using the Assembly API's transcribe model and when I run it on the server it returns that the video has no audio only text? any reason for this? I am providing youtube share links and I've tried the YouTube URL links as well? Suggestions for better FREE transcription API's would also be a valid solution just as long as they have decent readable documentation,Heres the code but its basically just a copy from the docs aside from the fact Im taking in user input transcriber = aai.Transcriber() #transcriber model def process_input(user_input): base_url = "https://api.assemblyai.com/v2" transcript_endpoint = "https://api.assemblyai.com/v2/transcript" response = requests.post(base_url + "/upload", headers=headers, data=user_input) upload_url = response.json()["upload_url"] data = { "audio_url": upload_url } response = requests.post(transcript_endpoint, json=data, headers=headers) transcript_id = response.json()['id'] polling_endpoint = f"https://api.assemblyai.com/v2/transcript/{transcript_id}" # run until transcription is done while True: transcription_result = requests.get(polling_endpoint, headers=headers).json() if transcription_result['status'] == 'completed': return transcription_result['text'] elif transcription_result['status'] == 'error': #the Error print HERE raise RuntimeError(f"Transcription failed: {transcription_result['error']}") -
Why does the 'UWSGI listen queue of socket full' error cause a Python application to time out during a third-party API call?
According to the logs, before the occurrence of "UWSGI listen queue of socket full", the third-party requests made by the application took only milliseconds. However, after this occurred, the same requests took more than ten seconds to complete. "I tried increasing the value of the listen parameter and the number of threads in uwsgi, which resolved the 5xx error in my application. However, my confusion is that the listen parameter should only affect the efficiency of receiving requests sent by nginx, so why does it affect calling third-party services?"