How to get Django template’s JavaScript’s session in Django view?

I ran test view below (The 1st run):

# "my_app1/views.py"

from django.shortcuts import render

def test(request):
    return render(request, 'index.html')

Then, I could set and get session in <script></script> in index.html as shown below (The 1st run):

{% "templates/index.html" %}

<script>
sessionStorage.setItem("test", "Hello");
console.log(sessionStorage.getItem('test')) // Hello
</script>

Next, I ran test view again with request.session.get(‘test’) but I could not get the session as shown below (The 2nd run):

# "my_app1/views.py"

from django.shortcuts import render

def test(request):
    print(request.session.get('test')) # None
    return render(request, 'index.html')

Actually, I could get a Django template’s JavaScript’s cookie in test view.

So, how can I get the Django template’s JavaScript’s session in test view?

Make Google programmable search use a different refinement tab by default

We are using the google programmable search.

we have multiple affiliate sites and each refinement is a different url. so we would like one url searchable by default but give the option for looking at other sites if needed.

How can we make a refinement tab the default instead of the all the refinements tab being selected.

Thanks for you help.

We looked through the regular google adjustments and didnt find a solution. so were looking for a coded solution

Download file via AJAX request for error handling if file does not exist/or cannot be downloaded

I am trying to use ajax request to do a download for my file. This is my code:

const downloadFile = (element) => { 
    $.ajax({
        url: element.id,
        type: 'GET',  
        success: (result) => {
            window.location=element.id;
        },    
        error: (request,msg,error) => {
            alert(request.responseText);
        }
    })
} 

And HTML element: 
'<td>' + `<a id=hiddenAPIRoute href="#" onclick="downloadFile(this)">Download</a>` + '</td>' +

I am able to download but it does a double download. I like using ajax so I can have better error handling. I am aware of the download attribute of html 5 but I want to include an alert for users to view if the file is not accessible.

Map not rendering, but console log does

I am trying to render a div that is supposed to display a purple square, through mapping an array of objects (box).
the square does not render, but console logging does work for some reason.

const FaceRecognition = ({ imgURL, box }) => {
  const Square = (box) => {
    box.map( (square,i ) => {
      return (
        <div key={i}
         className='bounding-box'
         style={{ top: square.topRow, right: square.rightCol, bottom: square.bottomRow, left: square.leftCol }}>
         {console.log("square calculated")}
        </div> 
      )
    })
  }
  return (
    <div className='center ma'>
      <div className="absolute mt2" >
        <img id='inputimage' src={imgURL} width='500px' height='auto' alt="" />
        {Square(box)}
        {/* <div className='bounding-box' style={{ top: box.topRow, right: box.rightCol, bottom: box.bottomRow, left: box.leftCol }}></div> */}
      </div>
    </div>
  )

}

enter image description here
i have attached an image of the code here if its any better than the body text

the square div was displaying normally when i tried rendering it through the parent function return, without mapping – where commented line is in the attached image.
i would love to see what im doing wrong here.

Is there a way to fix ChatGPT Service Error?

I opened chatGPT to debug my HTML code but it kept saying “Failed to get service”

I want this code to work

<html>
    <head>
        
    </head>
    <body>
        
    <script>
while True{
a=randomNumber;
b=randomNumber;
c=prompt((a+"+"+b));
if (c=(a+b)){
alert("Correct");
}
else{
alert("Wrong");
}
}
    </script>
     </body>
</html>

I want to code a program which gives a random number + random number math question but the Error says: Undefined Identifie

How to use JavaScript to tell if a value is a date

I have a table of data that needs to be sorted and in order to do so, I have to determine the datatype of the columns: numeric, text, or date. And no, I never know what the datatype of column will be and it will always have different data. I have to extrapolate the datatype by looking at the textcontent of the cell. The one I’m having an issue with is the date.

new Date(“MOD-001-01”) actually returns a real date of 1/1/2001.
new Date(“This is not a date 1”) also returns a real date, again 1/1/2001.

Is there any way to reliably test a value to see if its a date?

Search and replace in Visual Studio Code

I have a big number of files (10000) and inside each file I have a line containing this:

"image": "ipfs://example/1.png"

I need to replace 1.png with 1+n.png (starting from 1 and ending with 10000)

Could someone give me a solution to this ?
Thank you very much!

React JS .find Returns Undefined On Fresh Load

I am using .find in the React JS function, handleLikes(), below, which seems unstable. It returns undefined on a fresh load or reloads until I make a small change. It’s fully stable in another function, handleShowMore(), that I am using .find in. Can anyone provide advice?

    const getAPostLikeRecord = async (PostID) => {
        const url = process.env.REACT_APP_Backend_URL + '/post/get-like-record';

        await Axios.post (url, {
            PostsID : PostID
        })
        .then ((response) => {

            if (response.data.length !== 0) {
                response.data[0].didUserLike = false;
                setLikes(response.data);
                handleLikes();
            }
        })
        .catch((error) => {
            console.log(error)
            setStatusMessage("Server Side Error");
        });
    }

    const handleLikes = () => {
        const current_state = [...likes];
        const current_likes = current_state.find(l => l.postsLikeAuthor.trim() === loggedInUser);

        console.log(current_likes);
        
        if(!current_likes) {
            // couldn't find the post, ID's dont match
            return;
        }

        // replace the current state to the opposite
        current_likes.didUserLike = !current_likes.didUserLike;
        setLikes(current_state);
    }

Function successfully using .find.

    const handleShowMore = (post_id) => {
        const current_state = [...posts];
        const current_post = current_state.find(p => p.postsID === post_id);
      
        if(!current_post) {
            // couldn't find the post, ID's dont match
            return;
        }

        // replace the current state to the opposite
        current_post.displayMore = !current_post.displayMore;
        setPost(current_state);
    }

Prior to code change
Post to code change

API for audio player in web-site [closed]

I want to make my own website with an audio player, similar to spotify, like a pet project. I’m trying to find an api with free access (limited or not), where you can, for example, download music to a database (mongoDB or another, it doesn’t matter) And then output the music as a file to a site for listening.

I have found api so far that provide information in JSON about music, albums, playlists, but not in MP3. If you know any api or ways to implement this, I will be grateful for the help.
Stack: JS, Node js, reactJS( or htmlcss)

Refresh option missing on right click menu when on canvas

When I right click on a js canvas, the refresh page button is not available, is it possible to get the normal menu to pop up?

microsoft edge right clicked

Here is an example

<!DOCTYPE html>
<html>

<head>
  <title>Simple Drawing Program</title>
  <style>
    #canvas {
      border: 1px solid black;
    }
  </style>
</head>

<body>
  <canvas id="canvas" width="500" height="500"></canvas>

  <script>
    // Get the canvas element
    const canvas = document.getElementById('canvas');
    const context = canvas.getContext('2d');
  </script>
</body>

</html>

The Spread Operator in Javascript/Typescript/Angular

What does this 1st statement in the class mean?

export class ProductListComponent {
  products = [...products];
}

I have read something about the array spread operator. I understand that I can use it to add on to an existing array. However, the is the 1st statement in a class. ‘products’ is not even initialized?

Error resizing browser window in chrome extension

I am developing a chrome extension and I wanted to resize the browser window to a specific size. I am using the chrome.windows.update method. This is the following code

chrome.windows.getLastFocused(function (window) {
  var updateInfo = {
    width: 700,
    height: 600,
    top: 50,
    left: 100,
  };
  (updateInfo.state = "normal"),
    chrome.windows.update(window.id, updateInfo);
});

It does resize the window, but it resizes to 614×375 (on brave) and 544×433 (for chrome).

I am using manifest version 3.

Not sure where am i going wrong. Can you please help me out.

TIA.

google cloud “bucket.upload()” function is not working at all

async function uploadFile(filePath,destFileName) {
    const options = {
      destination: destFileName,
    };
    console.log("uploading file...");
    try{
      await bucket.upload(filePath, options);
    }
    catch(error){
      console.log(error);
    }
    console.log("upload successful");
  };

The bucket.upload() function does not seem to work at all. It does not give any errors or messages and it doesn’t even upload the file in the cloud as well.

The statement “uploading file is being logged in the console. But the statement “upload successful” is not logged, so I think the error should be in the bucket.upload() function. I have already checked the filePath and destFilePath and both of them are correct. I have also checked the bucket configuration and authorization, everything is fine.

The bucket.upload works perfectly fine outside the uploadFile() function and the uploadFile() is called with async keyword inside another function.(I don’t know if this is relevant to my problem but)

Update the image in Cloudinary after editing it using the API

I have a web application in Vue.js 3. I have a component where I render images and provide the option to edit them using the Cloudinary Media Editor. However, whenever I try to achieve it, I encounter an error (TypeError: Cannot read properties of undefined (reading ‘upload’) )

This function receives the event from Cloudinary after the user finishes editing the image:

     async handleSaveImageEdit(event) {
      
    // Organize data to pass to the updateImageCloudinary function

      const res = await updateImageCloudinary({
        path: secure_url,
        folder,
        transformation,
        public_id,
        shouldReplace: true,
      })

      console.log('res:', res)
      // Rest of the function
    },

event object looks like this:
event = {
assets: [ {
downloadUrl: ‘downloadUrl’,
secureUrl: ‘secureUrl,
url: ‘url,
} ],
transformation: ‘transformation string of the changes the user have done’
}

Then it goes to this function in another file:

import cloudinary from 'cloudinary-core'

const updateImageCloudinary = async ({ path, folder = '', transformation = '', public_id = '', shouldReplace = false }) => {
    const cloudinaryCore = new cloudinary.Cloudinary({ cloud_name: 'CLOUD_NAME' })

    const options = {
        folder: folder,
        overwrite: shouldReplace,
        raw_transformation: transformation,
        resource_type: 'image',
    }

    if (shouldReplace) {
        options.public_id = public_id
    }

    try {
        let result = await cloudinaryCore.uploader.upload(path, options)
        return result
    } catch (error) {
        console.error(error)
        throw error
    }
}

export default updateImageCloudinary;

As I mentioned before, the error you’re encountering in this function is:
TypeError: Cannot read properties of undefined (reading ‘upload’).

I have already ensured that I receive all the required properties as intended, and the Cloudinary cloud name is also correct.

Uploading a file with drop

I need to drag a file and collect its information: get its name and pass its content to Base64. When uploading the document doing the drop I get an error “Cannot read properties of undefined (reading ‘type’)” when I get to the if(event.dataTransfer.files[0].type !== “application/pdf”) line. Somehow I need to wait for it to load the document to handle the information. If I put a condition to enter if it receives a file, it skips the if and exits the function.
Attached is the simplified code.

import React, {useState} from "react";
import {
    Box,
    Button,
    Typography
} from "@material-ui/core";
import data from "./data.json"
import UploadFileIcon from "@mui/icons-material/UploadFile";

const Up = ({}) => {
    const [popUpConfirm, setPopUpConfirm] = useState(false);
    const [selectedFile, setSelectedFile] = useState();
    const [isFilePicked, setIsFilePicked] = useState(false);
    const [isLoading, setIsLoading] = useState(false);

    const handleSubmit = (event) => {
        event.preventDefault();
        setPopUpConfirm(true);
    };

    const changeHandler = (event) => {
        //changeHandler works
    };

    const handleDragOver = (event) => {
        event.preventDefault();
        event.stopPropagation();
    };

    const handleDrop = (event) => {
        event.preventDefault();
        setIsLoading(true);
        if(event.dataTransfer.files[0].type !== "application/pdf") {
            alert("Must be PDF.");
            return;
        }
        if(event.target.files) {
            setSelectedFile(event.dataTransfer.files[0]);
            setIsFilePicked(true);
            data.documentName = event.dataTransfer.files[0].name;
            getBase64(event.dataTransfer.files[0]).then(
                doc => data.document = doc
            );
        }
        setIsLoading(false);
    };

    //extracts the base64 content (removes the metadata at the beginning) and ensures padding is done correctly.
    function getBase64(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => {
                let encoded = reader.result.toString().replace(/^data:(.*,)?/, '');
                if ((encoded.length % 4) > 0) {
                    encoded += '='.repeat(4 - (encoded.length % 4));
                }
                resolve(encoded);
            };
            reader.onerror = error => reject(error);
        });
    }

    return (
        <>
            <form onSubmit={handleSubmit}>
                <Box onDragOver={handleDragOver} onDrop={handleDrop}>
                    <Box>
                        <Button >
                            {" "}
                            <UploadFileIcon/> Choose a document
                            <input type="file" name="file" onChange={changeHandler} hidden/>
                        </Button>
                        <Typography>Or drop your document here</Typography>
                        {isFilePicked ?
                            <Typography>
                                {selectedFile.name}
                            </Typography>
                            : null}
                    </Box>
                </Box>
                <Box>
                    <Button type="submit">
                        UPLOAD
                    </Button>
                </Box>
            </form>
            <UploadFile open={popUpConfirm} setOpen={setPopUpConfirm} data={data}/>  
        </>
    );
}

export default Up;