Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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?" -
Django - Mail is not sent
Email is not sent. What is interesting... before (like 3 mos ago) entire code worked perfectly fine. Settings: DEBUG = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT: 587 EMAIL_HOST_USER = 'xyz@gmail.com' EMAIL_HOST_PASSWORD = 'xyz' EMAIL_USE_TLS = True ALLOWED_HOSTS = [] view.py: def index(request): """The home page.""" # Send a message. if request.method != 'POST': # No data submitted; create a blank form. form_email = EmailForm() form_message = EmailMessageForm() else: # POST data submitted; proecess data. form_email = EmailForm(data=request.POST) form_message = EmailMessageForm(data=request.POST) if form_email.is_valid() and form_message.is_valid(): try: email = Email.objects.get(text=request.POST['text']) except: form_email.save() email = Email.objects.last() message_db = form_message.save(commit=False) message_db.email = email message_db.save() message_owner = ( f'New email on your website from {request.POST["text"]}', f"Email has been sent from: {request.POST['text']}\n\n" f"Full message:\n\"{request.POST['message']}\"", 'settings.EMAIL_HOST_USER', ['my@gmail.com',], ) message_guest = ('Your email has been sent', "Many thanks for getting in contact with me. Your message was " "successfully sent. I will reach out to you as soon as possible." f"\n\nYour message:\n\"{request.POST['message']}\"", 'settings.EMAIL_HOST_USER', [request.POST['text'],], ) send_mass_mail((message_owner, message_guest), fail_silently=False) return redirect('home:contact_thank_you') # Display a blank or invalid form. context = {'form_email': form_email, 'form_message': form_message} return render(request, 'home/index.html', context) Traceback: Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 4.1.5 Exception Type: TimeoutError Exception Value: [WinError 10060] Raised during: home.views.index C:\Users\danie\Desktop\python_work\page\home\views.py, line … -
Django - How to control 'add another' links in django-nested-admin areas
I have a very complicated object structure that the django admin section handles like a champ. As you can see below there are sub-references to other objects or even the same object. In many cases the sub objects are created in a certain pattern and I'd like to be able to generate stubs for that pattern. What i'd like to be able to do is I guess customize what happens when you click on the 'Add another Crafted Item' link, or add another link that will add multiple sub-item stubs. Right now if you click on that link, you get ONE stub with default values in it from the model object. I wanna do the same thing, but I want to be able to do more than one and be able to specify different default values than what are specified in the model object. Does anyone have any idea how I can tap into that functionality? Is there a name for it or something? thanks for the assistance, EK -
What is causing `tzlocal` to throw `Please use a timezone in the form of Continent/City. tzlocal() does not support non-zoneinfo timezones like UTC`?
Please use a timezone in the form of Continent/City. tzlocal() does not support non-zoneinfo timezones like UTC This was raised by requests.raise_for_status() My settings.py: USE_TZ = True TIME_ZONE = 'UTC' What is causing tzlocal to throw this? I couldn't find this error in other places. It usually complains about specific timezones but not 'UTC' -
Open ListView with foreignkey from anotherlist view using a slug in django
I was able to do basically what this article - link - says, and in the comments the person says that it would be beneficial to use a slug. How would I go about implementing the above article but with a slug. I understand how slug:pk works, I'm just not sure how to link that to a foreign key and have it filter by that pk, and then how to have it passed into the url as well. I don't really know where to start trying to figure this out, so any help at all is appreciated, Thanks(: -
Wagtail Sporadic 502 Errors in Image Admin
I am getting a 502 error when uploading new images to wagtail (this after uploading successfully many times since last update). The site runs on nginx. Sometimes, this leads to 502 error on the main image admin page, but these often clear with refreshing. This is the related error get in my Wagtail error log: Wagtail AttributeError: type object 'RequestContext' has no attribute 'locale' I expected this to resolve with reloading nginx and gunicorn and rebooting ubuntu. Unfortunately nothing works. I've also tried running a search for corrupt images and deleting all offenders. The problem remains. Have also tried uploading problematic images directly via SFTP which solves the problem temporarily, but doesn't allow for new uploads. I am using Django>=4.1,<4.2, wagtail>=5.0,<5.1 -
How to handle django static files for production
I am a newbie django developer and this is the django project i will be deploying. Everything works in development but I am been having issues in production. PS: I am using shared hosting for the deployment. First, the website loads but images are not showing. I tried using whitenoise but keeps getting the error File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/publishm/PUBLISHMYCRAFT/learnwithjdd/index/urls.py", line 12, in <module> path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('images/favicon_io/favicon.ico'))), File "/home/publishm/virtualenv/PUBLISHMYCRAFT/learnwithjdd/3.9/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 203, in url return self._url(self.stored_name, name, force) File "/home/publishm/virtualenv/PUBLISHMYCRAFT/learnwithjdd/3.9/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 182, in _url hashed_name = hashed_name_func(*args) File "/home/publishm/virtualenv/PUBLISHMYCRAFT/learnwithjdd/3.9/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 513, in stored_name raise ValueError( ValueError: Missing staticfiles manifest entry for 'images/favicon_io/favicon.ico' part of my urls.py from . import views from django.urls import path from . views import BlogHomeView, BlogDetailsView, AddPostView, EditPostView, DeletePostView, AddCategoryView, DraftsListView, AddDraftPostView, DraftPostDetailsView, EditDraftPostView, DeleteDraftPostView from django.views.generic.base import RedirectView from django.contrib.staticfiles.storage import staticfiles_storage app_name = 'index' urlpatterns = [ path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('favicon.ico'))) ] part of the settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "whitenoise.middleware.WhiteNoiseMiddleware", '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', ] STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / "staticfiles" STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" I tried using the whitenoise and play around with the path but the static files and the ckeditor are not working. The error disppears and … -
for loop for search engine not working properly
similar_entries = [] for entry in all_entries: for letters in entry: if letters in entry: if entry not in similar_entries: similar_entries.append(entry) This code is for a search engine but it is displaying all elements of the list instead of a showing strings with the same couple of words. all entries is a list I was stuck on this problem for so long