Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Value Error: Expected 2D array, got 1D array instead
I am just trying to learn the KNN algorithm. I am running the following code, but getting the following ValueError. import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score df = pd.read_csv(r"C:\Users\User\Downloads\Social_Network_Ads.csv") df = df.iloc[:,1:] #We dont need all the columns encoder = LabelEncoder() df['Gender'] = encoder.fit_transform(df['Gender']) #Encoding the gender col into 0 or 1 scaler = StandardScaler() X = df.iloc[:,0:3].values X = scaler.fit_transform(X) y = df.iloc[:,-1].values y = scaler.fit_transform(y) X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=10) knn = KNeighborsClassifier(n_neighbors=5) knn.fit(X_train,y_train) y_pred = knn.predict(X_test) print(accuracy_score(y_test,y_pred))` Exception: ValueError: Expected 2D array, got 1D array instead: array=[0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 1. 1. 1. 1. 1. 1. ... 1. 1. 1. 0. 1. 1. 1. 1. 0. 1. 1. 1. 0. 1. 0. 1. 0. 0. 1. 1. 0. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1. 0. 1.]. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample. -
python django asyncua subscription synchronous
In the following example, I call my function check_data_acknowledge from a synchronous function to subscribe to a node, determine the moment of its modification, and act accordingly. I have tried many solutions without finding a way to execute a subscription in my Django code If someone can help me, thanks in advance. import asyncio import time from asyncua.common.subscription import SubscriptionHandler from asyncua.sync import Client from prod_declarator.config_line import line_id from prod_declarator.opcua import opcua_instance def run_asyncio_function_synchronously(coro): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: return loop.run_until_complete(coro) finally: loop.close() async def subscribe_acknowledge(client, node_path): print(f"started subscribe_acknowledge at {time.strftime('%X')}") handler = SubscriptionHandler() subscription = await client.create_subscription(500, handler) nodes = node_path await subscription.subscribe_data_change(nodes) # Your asynchronous logic here counter = 0 while counter < 10: await asyncio.sleep(1) counter += 1 return subscription async def subscribe_acknowledge_sync(client, node_path): return await subscribe_acknowledge(client, node_path) def check_data_acknowledge(part_declaration_check_packaging_number): async def run_async(): node_data_acknowledge_line_id = opcua_instance.instanceExigences["data_acknowledge"] line_name = line_id[part_declaration_check_packaging_number["line_id"]]["lineName"] node_data_acknowledge = node_data_acknowledge_line_id.replace("LineName", line_name) print(f"Node data acknowledge : {node_data_acknowledge}") end_point = line_id[part_declaration_check_packaging_number['line_id']]["end_point"] name_space = line_id[part_declaration_check_packaging_number['line_id']]["associatedNameSpaceIndex"] print(f"Name space : {name_space}") client = Client(end_point, timeout=10) client.aio_obj.session_timeout = 600000 client.connect() node_path = client.get_node("ns={};s={}".format(name_space, node_data_acknowledge)) result = node_path.get_value() print(f"Result : {result}") await subscribe_acknowledge_sync(client, node_path) client.disconnect() loop = asyncio.get_event_loop() loop.run_until_complete(run_async()) return part_declaration_check_packaging_number In this code, check_data_acknowledge is called from another synchronous function like … -
How to redirect to different pages using a single form in django
I was trying to design a form which can be used to redirect the user to corresponding pages as per the selected category field. i am new to django I'm not sure where the error can be. Therefore, I am sharing all four files i.e. models, views, forms and templates (The urls are correct). models.py from django.db import models from autoslug import AutoSlugField # Create your models here. class Category(models.Model): name = models.CharField(max_length = 80, null = False, blank = False) slug = AutoSlugField(populate_from = 'name', unique = True) class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' def __str__(self): return self.name class Pdf(models.Model): pdf = models.FileField(upload_to="pdfs/") category = models.ForeignKey( Category, related_name = 'pdftools', on_delete = models.SET_NULL, blank = True, null = True ) def __str__(self): return f"{self.pdf}" views.py from django.shortcuts import render, redirect, get_object_or_404 import forms from django.contrib import messages # from .models import Category # from django.http import HttpResponseRedirect, HttpResponse # from django.urls import reverse # Create your views here. def linkview(request): return render(request, 'Link.html') def emailview(request): return render(request, 'Emails.html') def textview(request): return render(request, 'Text.html') def pdfUploadView(request): if request.method == 'POST': form = forms.UploadPdfForm(request.POST, request.FILES) if form.is_valid(): category = form.cleaned_data['category'] form.save() messages.success(request, "File uploaded successfully!!") # return HttpResponse('The file … -
Cannot use Model Form instance parameter with __init__ function
I am trying to create an edit form for a preexisting entry in one of my models. I need to limit the results for the select users field in my model form. However, when I try to use the instance=MyModelObject parameter for the form to load the prefilled from I get the error as follows. TypeError at /courses/course/asdd CourseForm.__init__() got an unexpected keyword argument 'instance' here is my view.py function @csrf_exempt @login_required def addCourse(request, course_id = None): #initialize data user = request.user school = user.school #check if submition is POST if request.method == 'POST': #if so check if user is linked to a school if user.school: #check if user has admin access to add courses if user.is_admin and user in school.admins: #get all form information # check if form data is valid if form.is_valid(): # save the form data to model form.save() return HttpResponseRedirect(reverse("courses", 'school')) #if GET check if user has a related school elif user.school: #check if user has admin access if user.is_admin: #check for course code, if so auto fill course info if course_id != None: #generate filled form course = Course.objects.get(code=course_id) form = CourseForm(instance=course, school=school) return render(request, "app/courses/addCourse.html", {'form': form}) #if no course code, generate blank form … -
Non-separation of elements
With this code, after pressing the close button, not only that product but all products will be sold, and the buyer cannot offer a price for any of them. views.py: @login_required def page_product(request, productid): product =get_object_or_404(Product, pk=productid) offers = Bid_info.objects.filter(product=product).order_by("-bid_price") off = Bid_info.objects.filter(product=product).order_by('id').first() # max bid try: bid_max = Bid_info.objects.filter(product_id=productid).latest('bid_price') except: bid_max ="No offer has been registered yet!" # close close_button = False try: if request.user == product.user: close_button = True off.bid_price = bid_max win = Bid_info.objects.filter(product_id=productid).order_by('id').latest("seller") for item in Bid_info.product: if item.id == Bid_info.product.id: Bid_info.checkclose = not Bid_info.checkclose else: close_button = False except: pass context = { 'product' : product,, 'offers' : offers, 'off' : off, 'close_button' : close_button, 'bid_max' : bid_max, 'checkclose' : Bid_info.checkclose, 'winner' : win } return render(request, 'auctions/page_product.html', context) def close(request, cid): return redirect(page_product, cid # bid def bid(request, bidid): product = get_object_or_404(Product, pk=bidid) if request.method == 'POST': user = request.user if user.is_authenticated: bid_price = Decimal(request.POST.get("bid_price", False)) other_off = Bid_info.objects.filter(product=product).order_by("-bid_price").first() if Bid_info.checkclose : messages.warning(request, "it sells.") else: Bid_ = Bid_info(product=product, seller=request.user, bid_price=bid_price) return redirect('page_product', bidid) If I delete the for loop in the first function and write this in the bid function in the if loop: if Bid_info.checkclose== true This is the situation again. html: … -
Location of signals in Django
I am confused about the use of signals. Where should I put the signal codes so that they are orderly and appropriate? I have a signal file for an app. Where do I call it? -
Is it possible to store a queue-like structure in Django database?
This might be a stupid question, but I'm new to databases and I could't find an answer anywhere. Is it possible to somehow store a FIFO queue in django? Some equivalent of python's collections.deque? Let's say I hypothetically have a model AverageRate, which stores a queue of up to 24 numbers and an average value of those numbers: (sum(numbers) / len (numbers)). class AverageRate: last_24_numbers = # FIFO queue up to 24 elements long average_value = # average value of last_24_numbers Every hour a function adds a new number to last_24_numbers and calculates average value. If the queue reaches 24 elements, then to append a new element to the end of the queue, it must pop the oldest element from the beginning of the queue. Honestly the only solution I came up with was to possibly convert the queue to string and store it in CharField, and then convert it back every time I need to use it. But I dunno... it just feels like not the best idea. I would obviously want to use the most efficient solution. -
How do I unfreeze or solve my python libraries being frozen problem
enter image description hereenter image description here I'm trying to make a test project and downloaded bootstrap in different ways but then this happened can anyone help me solve this. I tried deleting and downloading python again but that didnt work. -
How to create django model for tenants and properties?
2.2.Property Listing Module Property Details: Create property profile with information like Property name and address, location, features. Each property will have multiple units. Each unit will have features like rent cost,Type- 1BHK,2BHK,3BHK,4BHK property profile view with units and assigned tenant information 2.3.Tenant Management Module Create a tenant profile with name, address, document proofs. Assign a tenant with a unit under a property with details like agreement end date, monthly rent date. Need a search based on features added for units and properties. Show tenant profile view with personal information and rental information from django.db import models class Property(models.Model): name = models.CharField(max_length=100) address = models.TextField() location = models.CharField(max_length=100) features = models.TextField() def __str__(self): return self.name class Meta: verbose_name_plural = "properties" class Unit(models.Model): UNIT_TYPES = [ ('1BHK', '1BHK'), ('2BHK', '2BHK'), ('3BHK', '3BHK'), ('4BHK', '4BHK'), ] rent_cost = models.IntegerField() unit_type = models.CharField(max_length=4, choices=UNIT_TYPES) property = models.ForeignKey(Property, on_delete=models.CASCADE, related_name='units') def __str__(self): return f"{self.unit_type} unit in {self.property.name}" class Tenant(models.Model): name= models.CharField() address=models.TextField() document_proofs=models.ImageField() assigned_unit = models.ForeignKey(Unit, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self) -> str: return self.name This what I developed.Is this correct way of creating model. how to include agreement end date, monthly rent date in this model -
django AdminEmailHandler send sensitive information when include_html is False
i use django.utils.log.AdminEmailHandler for my logging hander class. in django docs, title was said as a security note to turn False include_html for not sending sensitive information. this is my Logging Config: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters':{ 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' }, }, 'handlers': { 'django_mail_logger': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler', 'include_html': False, }, }, 'loggers': { 'django': { 'handlers': ['django_mail_logger'], 'level': 'INFO', }, }, } as the note was mentioned in docs , i turn False the include_html to not send tranceback and etc but when error occurs my django app send traceback, settings and etc as when debug is false and only doesn't use HTML. is django docs correct or i misconfigure handler? i use django 4.2 and python 3.8. i try the logging configure which i mentioned and i expect email me less information but i receive sensitive informations. -
Why does django only allows access to the widget attributes when it renders a field into a form
I have a question about Django template rendering. Right now I use it to build a full-stack app, so the issue is that when I try to override a default form rendering behavior, I see that despite I can possibly overwrite default html without boilerplate, it is becoming harder as I dive deeper. Let's take a look on the excerpt from table.html which renders form as table. ... {{ field }} {% if field.help_text %} <br> <span class="helptext"{% if field.auto_id %} id="{{ field.auto_id }}_helptext"{% endif %}>{{ field.help_text|safe }}</span> ... Here we see that every form Field will render like <label> ~<input> <span> (help_text) But what if we want to overwrite default Field(e.g. ImageField) rendering behaviour to produce html portion like the below code to be able to add a preview avatar before the <input>-<help text> combination. <div> <img>(preview) <div> <input> <span>{{ field.help_text|safe }}</span> </div> </div> We can't just write custom html for our field, like django/forms/widgets/text.html, because it only has Widget in the context. So without boilerplate it is straightforward to overwrite how <input> tag is rendered using custom html files, but it is not straightforward how to make custom <label> and help_text rendering on per-field-class basis. Seems like we … -
Does Django CMS Support ASGI?
It seems like it should, given it supports Django 3, but I can't find any information about this at all. Searching the Django docs, the Django CMS docs, Google, here. Nothing relating to django cms specifically and asgi are returned. -
Django item swap
Please i need help implementing a feature in django where User A can request an item from User B and User B can choose to decline the request or choose to swap with one of User A items. class item_request(models.model): requester = models.foreignkey(User, on_delete=models.CASCADE) owner = models.foreignkey(User, on_delete=models.CASCADE) item = models.Foreignkey(Item, on_delete=models.CASCADE) status = models.CharField(max_length=30, default="pending") -
How DO I BLOCK URLS in django?
How to block urls in django? What I mean is if I have a website www.example.comand I want users to sign in before entering www.example.com/price and restrict users who will try to edit the URL in browser and enter? -
Hi, I am trying to create models in Django using Visual Studio. I am running the code in interactive and get errors
Here are the details - >>> from rntax6 import settings >>> # settings.configure(DEBUG=False) ... ... from asyncio.windows_events import NULL ... >>> from logging import NullHandler >>> from django.db import models >>> from django.db.models import Model >>> class Services(models.Model): ... service = models.CharField(max_length=255) ... class Meta: ... app_label = 'rntxapp6' ... Traceback (most recent call last): File "", line 1, in File "C:\Users\rabin03\source\pysrc\pyproj311\rntax6\env-rntx6\Lib\site-packages\django\db\models\base.py", line 129, in new app_config = apps.get_containing_app_config(module) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rabin03\source\pysrc\pyproj311\rntax6\env-rntx6\Lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "C:\Users\rabin03\source\pysrc\pyproj311\rntax6\env-rntx6\Lib\site-packages\django\apps\registry.py", line 137, in check_apps_ready settings.INSTALLED_APPS File "C:\Users\rabin03\source\pysrc\pyproj311\rntax6\env-rntx6\Lib\site-packages\django\conf_init_.py", line 91, in getattr val = getattr(wrapped, name) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rabin03\source\pysrc\pyproj311\rntax6\env-rntx6\Lib\site-packages\django\conf_init.py", line 293, in getattr return getattr(self.default_settings, name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'str' object has no attribute 'INSTALLED_APPS' def str(self): ... return self.name ... The last part floors me. Any help would be very much appreciated. I have tried changing the Settings a number of different ways but get even more errors. -
I got athentication error when im trying to post a request using axios api in vue.js
commerce website and this is my checkout.vue code when post request an authenticated error 401 and i don't know where the problem is some says its becuase axios and i should replace it with fetch api,any suggestion? const data={ 'first_name':this.first_name, 'last_name':this.last_name, 'eamil':this.eamil, 'address':this.address, "zipcode":this.zipcode, "place":this.place, "phone":this.phone, "items":items, 'stripe_token':token.id } await axios .post("/api/v1/checkout/",data) .then(response=>{ this.$store.commit("clearCart") this.$router.push("/cart/success") }) .catch(error=>{ this.errors.push("Something went wrong. Please try again") console.log(error) }) this.$store.commit('setIsLoading',false) } -
CSRF Failed: CSRF token missing django REST + Vuejs obtain_auth_token
I am making POST request to get the token from the backend. I have traefik to provide https for security reason. It works. But when I deploy Vuejs and make POST with the same payload. I got the error in the Chrome browser. detail: "CSRF Failed: CSRF token missing." I have search over the stackoverflow. I would like to follow the security concept then disable CSRF is not an option. import {ref} from "vue"; import {BACKEND_URL} from "../constants"; const getLoginToken = () => { const token = ref('') const tokenError = ref(null) const fetchToken = async(username, password) => { try{ const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ "username": username, "password": password }), redirect: 'follow', } const url = BACKEND_URL + '/api/auth-token/' console.log(url) let data = await fetch(url, requestOptions) if(!data.ok){ throw Error(data.statusText) } token.value = await data.json() } catch(err){ tokenError.value = err.message console.log(tokenError.value) } } return { token, tokenError, fetchToken } } export default getLoginToken settings.py REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 10, "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", ), 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.DjangoFilterBackend', ), "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",), "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", } `urls.py from django.views.decorators.csrf import csrf_exempt ... path("api/auth-token/", csrf_exempt(obtain_auth_token)), ... But does not work. Problem: I am unable to … -
Friendly duration picker ready to be used as a form widget in a Django application
I need to let a user select a duration in a form field of a Django application. I'm already using bootstrap (namely django-bootstrap-datepicker-plus) to select other fields such as Date, Time and DateTime. But duration is something lightly different. I'm currently having a simple integer field where the user is asked to input the duration value in minutes. But once the duration last for some hours, e.g. 07h24, the user has to compute to how many minutes it corresponds before entering the right value. This is error prone. On the opposite, if I ask the user to input values in hours, 7h20 would become 7.3333. This is also error prone and it's not precise in that case. That's why I'm searching for a true duration picker. Using two DateTime pickers and computing the timedelta is also not an option for the lack of user-friendliness. Hence my question: does a friendly duration picker exists inside bootstrap for Django and if not, does something other exist? I guess I don't have to reinvent the wheel, but I wasn't able to figure out something which integrates well with Django 4. Ideally, jQuery should also be avoided. My current research led me to these … -
How to setup email verification with Django-Verify-Email
I get an invalid link in the email every time i register a new user with this package here is my code def signup(request, form_class, template_name, success_message, redirect_url): if request.user.is_authenticated: return redirect(redirect_url) form = form_class() if request.method == 'POST': form = form_class(request.POST) if form.is_valid(): send_verification_email(request, form) form.save() messages.success(request, success_message) return redirect(redirect_url) else: messages.error( request, f'Error creating account. Please check the form.') return render(request, template_name, {'form': form}) context = {'form': form} return render(request, template_name, context) def student_signup(request): return signup( request, StudentRegistrationForm, 'user/student/signup.html', 'Student account created successfully.', 'user:signin' ) Am i just using the standard setting. Am i missing anything? -
Error 508 Invalid data in MERCHANT_ID field. Please contact the merchant
Can anyone help me understand why do I get this error? I used the merchant_id that I was given at https://developer.globalpay.com/ <<script> $(document).ready(function() { $.getJSON("sdkRequestEndpoint", function(jsonFromRequestEndpoint) { RealexHpp.setHppUrl("https://pay.sandbox.realexpayments.com/pay"); RealexHpp.lightbox.init("payButtonId", "responseEndpoint", jsonFromRequestEndpoint); }); }); </script> <!DOCTYPE html> <html lang="en"> <head> <!-- Add these links in the head section of your HTML file --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css"> <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script> </head> <body> <center> <h2>Make a Booking</h2> <form action="https://pay.sandbox.realexpayments.com/pay" method="POST" target="iframe"> <input type="hidden" name="TIMESTAMP" value="20180613110737"> <input type="hidden" name="MERCHANT_ID" value="MER_7e3e2c7df34f42819b3edee31022ee3f"> //my Merchant_ID <input type="hidden" name="ACCOUNT" value="internet"> <input type="hidden" name="ORDER_ID" value="N6qsk4kYRZihmPrTXWYS6g"> <input type="hidden" name="AMOUNT" value="1999"> <input type="hidden" name="CURRENCY" value="EUR"> <input type="hidden" name="AUTO_SETTLE_FLAG" value="1"> <input type="hidden" name="COMMENT1" value="Mobile Channel"> <input type="hidden" name="HPP_VERSION" value="2"> <input type="hidden" name="HPP_CHANNEL" value="ECOM"> <input type="hidden" name="HPP_LANG" value="en"> <!-- Begin 3D Secure 2 Mandatory and Recommended Fields --> <input type="hidden" name="HPP_CUSTOMER_EMAIL" value="test@example.com"> <input type="hidden" name="HPP_CUSTOMER_PHONENUMBER_MOBILE" value="44|789456123"> <input type="hidden" name="HPP_BILLING_STREET1" value="Flat 123"> <input type="hidden" name="HPP_BILLING_STREET2" value="House 456"> <input type="hidden" name="HPP_BILLING_STREET3" value="Unit 4"> <input type="hidden" name="HPP_BILLING_CITY" value="Halifax"> <input type="hidden" name="HPP_BILLING_POSTALCODE" value="W5 9HR"> <input type="hidden" name="HPP_BILLING_COUNTRY" value="826"> <input type="hidden" name="HPP_SHIPPING_STREET1" value="Apartment 852"> <input type="hidden" name="HPP_SHIPPING_STREET2" value="Complex 741"> <input type="hidden" name="HPP_SHIPPING_STREET3" value="House 963"> <input type="hidden" name="HPP_SHIPPING_CITY" value="Chicago"> <input type="hidden" name="HPP_SHIPPING_STATE" value="IL"> <input type="hidden" name="HPP_SHIPPING_POSTALCODE" value="50001"> <input type="hidden" name="HPP_SHIPPING_COUNTRY" value="840"> <input type="hidden" name="HPP_ADDRESS_MATCH_INDICATOR" value="FALSE"> <input type="hidden" name="HPP_CHALLENGE_REQUEST_INDICATOR" value="NO_PREFERENCE"> <!-- … -
Custom user model vs. additional model
Due to lack of knowledge, when faced with the need to store additional information about users, I created additional UserInfo model and referenced it by foreign key to the standard User model. I have since learned two things: It is recommended to have a custom user model. It is tricky to switch mid-project (this being the best way so far as far as I understand). I would like to understand: If the fields in UserInfo are not used for authentication, is there any reason to merge those into the user model? What do I stand to gain by taking the time to abandon my current approach and switch to a custom user model? -
React and Django deployment blank page and 404 errors on static files with cpanel
I wanted to deploy my django and react application on my domain name via my host I have setup my python because when we go to the url dimitridenis.com/admin we arrive at my django admin portal, I implemented React and did the npm install then the build in my cpanel terminal, however I found myself with a white screen and 404 errors on static files, I tried several times to change my build, the paths in my settings.py file but I still don't understand White screen with errors If you have any ideas to give me, I'm interested -
Can we use django-distill to host a Django website in Github pages?
I'm exploring options for hosting a Django website on GitHub Pages, and I came across the django-distill package. I'm wondering if it's feasible to use django-distill for hosting a Django website on GitHub Pages. Here are some specific points I'm curious about: *Has anyone successfully used django-distill to deploy a Django website on GitHub Pages? *Are there any specific configurations or steps that need to be taken to make it work with GitHub Pages? I appreciate any insights or experiences you can share regarding using django-distill or any other approach for deploying a Django site on GitHub Pages. I attempted to use django-distill to deploy a Django website on GitHub Pages. My approach involved configuring django-distill and following the standard steps for deploying a Django project. However, despite my efforts, I encountered challenges, and the deployment did not work as expected. Link: https://django-distill.com/ -
Uncaught TypeError: Cannot read properties of null (reading 'defaultPrevented')
seem to be getting a script error that mentions both bootstrap alert and my own close alert tag. I have a script that closes alerts after 2.5s when a script is created. It is tied to user actions, for example if a user creates a blog post or deletes a comment, an alert shows with the User task and then auto closes the tag. i seem to be getting a Uncaught TypeError in console and cant figure out why, i can only speculate that its because its looking for a alerts msg that isnt there yet? script.js // // Event listener for auto close message function using DOM Content Loaded // // Javascript function for auto close messages // document.addEventListener("DOMContentLoaded", alertTimeout); document.addEventListener("DOMContentLoaded", (alertTimeoutalertTimeout) => { setTimeout(function () { let messages = document.getElementById("msg"); let alert = new bootstrap.Alert(messages); alert.close(); }, 2500); }); index.html bootstrap script <!-- Bootstrap Scripts --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> </html> Console Error code Uncaught TypeError: Cannot read properties of null (reading 'defaultPrevented') at Q.close (alert.js:38:60) at script.js:11:11 close @ alert.js:38 (anonymous) @ script.js:11 setTimeout (async) (anonymous) @ script.js:7 I have tried to add a document ready to the script and have tried different … -
django get all the likes made for a post
i am trying to get all the likes for a specific in the home templates and also they are many products in the template. this is my views.py @login_required def home(request): products = Product.objects.all() like_counts = {product.id: Like.objects.filter(product=product).count() for product in products} liked_products = Like.objects.filter(user=request.user, product__in=products).values_list('product', flat=True) context = { "products": products, "liked_products": liked_products, "like_counts": like_counts, "categories": Category.objects.all(), } return render(request, 'shop/index.html', context) @login_required def likeProduct(request, product_id): product = get_object_or_404(Product, id=product_id) # Check if the user has already liked the product if not Like.objects.filter(user=request.user, product=product).exists(): # Create a new Like object Like.objects.create(user=request.user, product=product) print('product liked') likes = Like.objects.all().count return JsonResponse({"status": "success","likes":f'{likes}'}) else: liked = Like.objects.get(user=request.user) liked.delete() print('product like removed') likes = Like.objects.all().count return JsonResponse({"status": "success","likes":f'{likes}'}) def views_count(request,product_id):` item = Product.objects.get(id=product_id) item.views_count += 1 item.save() return redirect('home') this is my index.html and i am got stuck here now the django is giving all sorts of weird errors and do not know how to solve it: {% csrf_token %} <div class="d-flex justify-content-between"> <button onclick="likeProduct({{ product.id }})" class="btn shadow-none bg-transparent rounded-pill"> <i class="{% if product.id in liked_products %}fas{% else %}far{% endif %} fa-heart"></i> {{ like_counts|default:"0"|get:product.id }} </button> <button class="btn shadow-none bg-transparent rounded-pill"><i class="fas fa-star"></i></button> <button class="btn btn-outline-primary"><i class="fas fa-comment"></i></button> </div>