Host blocked

I’m writing an extension for chrome. I need to open a file on the path chrome-extension://id/folder/index.html, on my computer everything opens, but when I try to open it on my laptop it says host blocked.
(Extension unzipped)

How can I solve this problem?
P.S. I use manifest v3.

I tried to find something in the documentation and couldn’t find it.
On all computers except my primary host is blocked

JavaScript Proxy not working for opened Window object

I need to Proxy a window object opened with window.open.

So far as I understand it (which is not well), the trivial “handler” here should effectively be the identity operation, passing thru property accesses unmodified:

let origOpen = window.open;
window.open = function(url) {
  let openedWindow = origOpen.apply(this, arguments);
  let handler = {
    get(target, prop, receiver) {
      return Reflect.get(...arguments);
    }
  };
  let wrappedWindow = new Proxy(openedWindow, handler);
  return wrappedWindow;
};

let wi = window.open("https://example.net/");
console.log(wi.closed);

However, when this script reaches the line which tries to log wi.closed, it throws the following exception:

Uncaught TypeError: 'get closed' called on an object that does not implement interface Window.

(Using Firefox ESR 115.)

How do I go about creating a “clone” of a web browser game? [closed]

I am a very beginner programmer who took a C++ class in high school and learned R in college. I have been playing the cine2nerdle game where you battle another random player by linking movies together via cast members until one person runs out of time or cannot think of another link in the chain.

A friend and I enjoy playing this, but are left wishing there was a version for tv shows rather than solely movies. At first it seems like a simple copy and paste but I have no idea where to begin due to little coding knowledge. I have been looking up basic js to start but not sure how exactly to get the proper apis involved to grab the tv data like actors. If anyone has any idea on how to build something like this even if it’s just a local game so I can play with my buddy and surprise him for his birthday. Any responses are appreciated thank you.

Tried looking at the code from inspect element and copying and pasting into visual, but I get a very broken and text only version of the homepage.

Parsing data from python into javascript to then put into Chart JS

Originally I had a basic line chart. I then tried to parse data into the js portion of the html using jinja but obviously that didn’t work. I then tried to parse directly into js. Unsuccessful. Now I tried using a json file and grabbing the values. Again Unsuccessful.

Currently trying to iterate over it and it’s not working
I tried parsing through js, unsuccessful, tried jinja, tried using a json file

fetch('Solo-Trade-Journal/monthly_data.json')
    .then(response => response.json())
    .then(data => {
        // Parse the JSON data and extract the dates and growth values
        var labels = data.map(item => item.date);
        var growth = data.map(item => item.growth);

        // Select the canvas element and create a new Chart object
        var ctx = document.getElementById('myLineChart').getContext('2d');
        var myLineChart = new Chart(ctx, {
            type: 'line', // specify the chart type
            data: {
                labels: labels, // these labels appear on the x-axis
                datasets: [{
                    label: 'My First Dataset', // the name of this dataset (optional)
                    data: growth, // the data points for this dataset
                    fill: false, // don't fill the area under the line
                    borderColor: 'rgb(75, 192, 192)', // the color of the line
                    tension: 0.1 // the smoothness of the line
                }]
            },
            options: {
                responsive: true, // make the chart responsive
            }
        });
    });
# Iterating over data and extracting required information
        monthly_list = []
        for entry in data['data']:
            data_info = {
                'date': entry['date'],
                'growth': entry['growth'],
            }
            monthly_list.append(data_info)

        # Printing the list of data dictionaries
        print("Data list:", monthly_list)
        monthly_list_json = json.dumps(monthly_list)
        # Writing the data to a JSON file
        with open('monthly_data.json', 'w') as f:
            f.write(monthly_list_json)

Issue with accessing data in ‘updateUser’ method with Supabase

Firstly, I’d like to say that I am just starting with programming and not sure if the provided details are sufficient.

I’m encountering an error when trying to access data within the updateUser method in Supabase.

Supabase docs – Update user

  const updateUserMetadata = async (formData) => {
    const idSegmentOne = Math.floor(Math.random() * 1e10).toString()
    const idSegmentTwo = Date.now().toString()
    const id = idSegmentOne + idSegmentTwo
    const snippet = {id: id, name: formData, body: input.input}

    try {   
      const { data, error } = await supabaseClient.auth.updateUser({
        data: { mdSnippets: [ ...data.user.user_metadata.mdSnippets, snippet ] }
      })

      // console.log(data)

      error
        ? toast.error('Saving snippet failed.')
        : toast.success('Snippet saved successfully.')
      console.log('Updating metadata error (try):', error)
    } catch (error) {
      toast.error('Saving snippet failed')
      console.log('Updating metadata error (catch):', error.message)
    }
  }

I believe that the problem is related to spreading the existing values in the array:

[ …data.user.user_metadata.mdSnippets, snippet ]

When attempting to access the data object to spread those values, I’m getting Cannot access ‘data’ before initialization error. The error comes from the catch block console log.

The function is called from another component in the following way:

  const onSubmit = (formData) => {
    updateUserMetadata(formData.snippetName)
    // getUserMetadata()
  }

I think that I am trying to access the relevant key-value pair in the correct way as I have checked the shape of the object with the commented out console log you can see after the try block.


I’ve tried declaring data as empty object before the try block, like below, but I am not even sure if that applies to the scope of the try block (I think it doesn’t) since the data in thy block is deconstructed from the Supabase method.

let data = {}

Tried setTimeout to see if maybe after some time the data object would be initialized, but it is not (also tried longer time intervals than 1 second).

try {
  const { data, error } = await supabaseClient.auth.updateUser({
    data: {
      mdSnippets: await new Promise((resolve) => {
        setTimeout(() => {
          resolve([...data.user.user_metadata.mdSnippets, snippet])
        }, 1000)
      })
    }
  })

But… everything works as expected if I modify the array to contain only the snippet without spreading existing data.

    try {   
      const { data, error } = await supabaseClient.auth.updateUser({
        data: { mdSnippets: [ snippet ] }
      })

Thanks

Build a calculation drill for maths squares and cubes

Write a program that asks me minimum and maximum value then starts asking cubes of numbers between those values. Next step is optional but will be appreciated And it should ask same number once till each number is asked then it can repeat randomly again for another cycle

Same for squares

For reference this is for multiplication –>

https://sagecell.sagemath.org/?z=eJydVc1unDAQvvMUrnuBbna3aS9NFpCSJlIqJWoURaoq5WKMWawYe2vMbrZVnqMP1Bfr-IddiLRSWg5gZub75vPMGNI3F18_33-_vUS1aUQepf2DkRIeDTME0ZrolpkMd6aafsK9WZKGZXjN2WaltMGIKmmYhLANL02dlWzNKZu6F4sx3AiW33TC8JXglBiuJLrQXIh07n1ROg9pC1VurYiPB-LBEaVcrjqDeJlhcq0wMtsVyJFdUzCN0ZqIDl4_4DwVpGACVUr7wPxabdBZOnfmPC30mOqKH6A6OXnBBZH5FV_Wh8mK1-oqel3nB6leravY6RqTQVU7Y6CGSlKo52OGNYOuxgnO7-winXu_Lb_uISVfu_QN4dI2sX__0fGfkHYO7yOZQLlSsmUvtULOmsglWGjN6GM8MTVvZ24HieUd6N9R5Gey3TDdb2Iva6dipVXZUbMX0j_C_LRU85XJozXRKMSiDL0_QhrKE5YbreTSLhdRVHWSujE7334p4zb5FSG4NDOdlqhUtGtgvmdLZi4Fs8sQtoieB1hw3xFZqiZuuDxCDXka89wQU88qoZSO3VL74AS9QzEEoykCHJqg4wRusHxJr-LAJ5hBMNCgfeKEuOlOfFGPEIznwAMz0Xsc1l_FEF0M0cUQXezRUKRdagjY7xVyu5wJYEeOwjqAAbZhkfs2ENhw4Y0-za7xIRfEYDxIqDoLw3e2d6cIQ3V8Gyew_ma76I2-odZ4rwwR3hj3oc5rK4sf5IPEPr9lnlhFFvXnt0OMpLlxT2ZcSqbv2ZPVAZhxY_xgg_LQHo_sR3QMxrcavo6qa726EOQz8gpZFpRlvT0Quhny28jQ8WJn84ncCU1mrdkKV7mC0MelVp0sp1QJpU_RW1rRsOFnd2eiZXvqULf_o67omNpO6bg84WMTjkI4f4PD92_pqiqk2yUK_As4_f2xh_-E_Zn9BZr2GSM=&lang=html

I dont know programmin so please help

Can someone fix the 405 error I’m getting

So I created a node.js code that takes form data and sends it with nodemailer to my Gmail but anytime I submit the code it gives a 405 error that says cannot GET/ submit

This is the code

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');

const app = express();
const PORT = process.env.PORT || 3000;

// Middleware

app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(express.static(path.join(process.cwd(), 'public')));

// POST route for form submission
app.post('/submit', async(req, res) => {
  const formData = req.body;

  try {
    // Create SMTP transporter
    const transporter = nodemailer.createTransport({
      host: 'smtp.gmail.com',
      port: 465,
      secure: true,
      auth: {
        user: 'my Gmail',
        pass: 'my Gmail password' // Use your Gmail app password here
      }
    });

    const html = `
            <h2>New Form Submission</h2>
            <p>First Name: ${formData.firstName}</p>
            <p>Last Name: ${formData.lastName}</p>
            <!-- Add other form fields here -->
        `;

    const mailOptions = {
      from: '[email protected]',
      to: '[email protected]',
      subject: 'New Form Submission',
      html: html
    };

    // Send email
    const info = await transporter.sendMail(mailOptions);
    console.log('Email sent: ' + info.response);
    res.status(200).send('Email sent successfully');
  } catch (error) {
    console.error('Error sending email:', error);
    res.status(500).send('Error sending email');
  }
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

I ‘ve tried so many things but it’s not working as well
This is my JavaScript code

$(document).ready(function() {
  $('form').submit(function(event) {
    event.preventDefault();

    var formData = $(this).serialize();
    $.ajax({
      type: 'POST', // Ensure it's a POST request
      url: '/submit', // Correct endpoint
      data: formData,
      success: function(response) {
        console.log('Email sent successfully');
      },
      error: function(error) {
        console.error('Error sending email:', error);
      }
    });
  });
});

Unable to Fetch Data from Node.js Server on Devices Other Than Hosting Device

I’m encountering an issue where I can’t establish a connection to my server from devices other than the one hosting the server. The server is running locally, and I’m developing a web application using React as the frontend.

When I access the application from the hosting device (e.g., my laptop), everything works fine. However, when attempting to access the same application from other devices on the same network (i’ve tried with both iPhones and Androids), I’m unable to fetch data from the server. I can get to the page but there no data being loaded, (From Mac (Hosting Device)From Other Device Same Network.

Upon inspecting the network activity using the web inspector, I noticed that all the failed requests have a type of “fetch” and a domain of “localhost”. On the other hand, successful requests, have types like “txt”, “js”, “document”, “socket”, etc., with the domain being my IP address.

I’ve checked my CORS configuration, and it seems to allow requests from any origin. Additionally, I’ve ensured that the server is running and accessible from the client devices by trying to access it directly through a web browser.

More things I have tried:

  1. Verified that both my Mac and iPhone are connected to the same Wi-Fi network.
  2. Disabled firewall restrictions on my Mac, all incoming connections are allowed.
  3. Confirmed that the server is configured to allow CORS from all origins (Access-Control-Allow-Origin: *).
  4. Tested accessing the server from phones using different web browsers

I expected the data to load successfully like when accessing it from the host device.

What’s the difference between my SSN Regex and the Regex that Trellix has for SSN validation?

So I’ve been working on some website validation in javascript and I am pretty new to using Regex. This is the Regex I created to validate Social Security Numbers that have a hyphen in between the three sections.

/^d{3}[-]d{2}[-]d{4}$/

and then In my research I came across a site called Trellix and I’ll attach a link to their site where I found it because they have a lot more Regex than just the SSN that I’m interested in. This is there Regex code that validates for hyphens in between the three sections

/(?:b(?:0[1-9][0-9]|00[1-9]|[1-5][0-9]{2}|6[0-5][0-9]|66[0-5789]|7[0-2][0-9]|73[0-3]|7[56][0-9]|77[012])-(?:0[1-9]|[1-9][0-9])-(?:0[1-9][0-9]{2}|00[1-9][0-9]|000[1-9]|[1-9][0-9]{3})b)/

Their Regex is a lot longer than mine and as far as I can tell from comparing mine to theirs on regex101.com I am unable to tell a difference they both seem to work and do the same thing. If so why is theirs so much longer? Does it account for something more I’m not realizing? Is my Regex good enough for this case of validation?

If Trellix Regex is better should I try to use more of their Regex listed on their site for my own purposes?

Trellix.com

Why is the console.log() method within quotations?

I’m still very new to JavaScript and I recently read through the documentation for setTimeout() and saw the following example:

setTimeout("console.log('Hello World!');", 500);

How does this work? Are we not making console.log() a string? I tried to find more information about this but I don’t really know where to look or how to properly ask the question. Does this apply to all functions and methods? And if so, what determines if I need to use quotation marks or not?

I tried the above sample and it works, I just don’t understand why it works since it seems like we make the whole thing into a string.

Using Webpack’s development mode when building subproject makes importing the subproject fail

I’m building a Webpack project that makes use of a class exported by another Webpack project. The whole project’s structure looks something like this:

dist
  | app.js // Generated by Webpack from src/app.js
src
  | app.js
subproject
  | dist
  |   | app.js // Generated by Webpack from subproject/src/app.js
  | src
  |   | app.js
  | package.json
  | webpack.config.js
index.html
package.json
webpack.config.js

The superproject’s app.js uses import Subproject from 'subproject' to import a class exported by the subproject.

When the subproject is built using Webpack’s production mode, this works fine. But when I switch the subproject to development mode, the superproject no longer seems to get what it needs when importing the subproject:

Uncaught TypeError: subproject__WEBPACK_IMPORTED_MODULE_0___default() is not a constructor

Similarly, if I keep the subproject in production, but change the superproject to production as well, it also fails:

Uncaught TypeError: __webpack_require__.r is not a function

My main question is: Why is this happening? Any thoughts, questions, or answers you can share are helpful.

But also: Is exporting the subproject as a commonjs module a bad idea? Is loading it in the superproject with the import keyword a bad idea? Is this just not something development mode supports? Is there something about my setup here that just looks wildly out of whack?

Replicating the issue

To replicate the issue, let’s try something simple:

subproject/src/app.js exports a class with a single method returning 'foobar':

export default class Subproject {
    test() {
        return 'foobar';
    }
}

src/app.js imports the subproject and tries to use it:

import Subproject from 'subproject';

const subobj = new Subproject();
console.log( subobj.test() );

This should log foobar to the console.

webpack.config.js is straightforward:

const path = require('path');

const root = __dirname;
const src  = path.resolve( root, 'src' );

module.exports = {

    mode: 'development', // <-- THIS WORKS
    // mode: 'production', // <-- THIS DOESN'T

    context: src,

    resolve: {
        preferRelative: true,
        extensions: [ '.js' ],
        modules: [
            path.resolve( src, 'modules' ),
            'node_modules',
        ],
        alias: {
            'subproject': path.resolve( root, 'subproject' ),
        },
    },

    entry: {
        'app': 'app.js',
    },

    output: {
        filename: '[name].js',
        path: path.resolve( root, 'dist' ),
        publicPath: '/dist/',
        clean: true,
    },

    optimization: { runtimeChunk: 'single' },

};

As is subproject/webpack.config.js:

const path = require('path');

const root = __dirname;
const src  = path.resolve( root, 'src' );

module.exports = {

    mode: 'production',  // <-- THIS WORKS
    // mode: 'development', // <-- THIS DOESN'T

    context: src,

    resolve: {
        preferRelative: true,
        extensions: [ '.js' ],
        modules: [
            path.resolve( src, 'modules' ),
            'node_modules',
        ],
    },

    entry: { 'app': 'app.js' },

    output: {
        filename: '[name].js',
        library: { type: 'commonjs' },
        clean: true,
    },

    optimization: { runtimeChunk: 'single' },

};

subproject/package.json defines main: 'dist/app.js'.

An index.html loads the runtime and the app:

<script src="/dist/runtime.js" charset="utf-8"></script>
<script src="/dist/app.js" charset="utf-8"></script>

You’ll need to build the subproject first, then the superproject. Finally, visit index.html to see what you’ve wrought.

How to add js codes to newly added list items [duplicate]

uhmn, I created an unordered list with a js code running on each of the list items but when I add new list items with an input tag, the code does not affect them.

I tried looping through the list to get each items individually and add the code to both the previous items and the newly added ones but the code was only added to the previous list items neglecting the new ones.

let ul= document.getElementsByClassName("ul")[0];
let list= ul.getElementsByTagName("li");

function listLength() {
  return list.length;
};

for (let i=0; i<listLength(); i++) {
  list[i].addEventListener("click", toggleList);
  function toggleList() {
    return list[i].classList.toggle("done");
  };
};

jQuery script does not apply bootstrap classes to my form

**Why does my jQuery code not color the rows when conditions are met (I made the specific part of the script italic)?
**

HTML CODE for the POLL:

<form id="pollForm" class="mb-4">
          <div class="form-group">
            <label for="pitanje1"
              >Koliko ste zadovoljni lokacijom FUTURA Shopping Centra?</label
            >
            <select id="pitanje1" name="pitanje1" class="form-control">
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
            </select>
          </div>
          <div class="form-group">
            <label for="pitanje2"
              >Koliko ste zadovoljni radnjama u FUTURA Shopping Centru?</label
            >
            <select id="pitanje2" name="pitanje2" class="form-control">
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
            </select>
          </div>
          <div class="form-group">
            <label for="pitanje3"
              >Koliko ste zadovoljni izgledom FUTURA Shopping Centra?</label
            >
            <select id="pitanje3" name="pitanje3" class="form-control">
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
            </select>
          </div>

          <button
            type="button"
            class="btn btn-dark mt-2"
            onclick="saveAnswers()"
          >
            Pošalji
          </button>
        </form>
        <table class="table">
          <thead>
            <tr>
              <th>Pitanja</th>
              <th>Prosečna ocena</th>
            </tr>
          </thead>
          <tbody id="resultsTableBody">
            <tr id="row1">
              <td>Koliko ste zadovoljni lokacijom FUTURA Shopping Centra?</td>
              <td id="prosecnaOcena1">0</td>
            </tr>
            <tr id="row2">
              <td>Koliko ste zadovoljni radnjama u FUTURA Shopping Centru?</td>
              <td id="prosecnaOcena2">0</td>
            </tr>
            <tr id="row3">
              <td>Koliko ste zadovoljni izgledom FUTURA Shopping Centra?</td>
              <td id="prosecnaOcena3">0</td>
            </tr>
          </tbody>
    </table>
 

jQuery and bootstrap imports with the logic code:

    <script src="js/bootstrap.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>
      const answersData = {
        pitanje1: { ukupnaOcena: 0, brOdgovora: 0 },
        pitanje2: { ukupnaOcena: 0, brOdgovora: 0 },
        pitanje3: { ukupnaOcena: 0, brOdgovora: 0 },
      };

      function saveAnswers() {
        const pitanje1 = parseInt($("#pitanje1").val());
        const pitanje2 = parseInt($("#pitanje2").val());
        const pitanje3 = parseInt($("#pitanje3").val());

        updateAnswer("pitanje1", pitanje1);
        updateAnswer("pitanje2", pitanje2);
        updateAnswer("pitanje3", pitanje3);

        updateResultsTable();
      }

      function updateAnswer(pitanje, vrednost) {
        answersData[pitanje].ukupnaOcena += vrednost;
        answersData[pitanje].brOdgovora++;
      }

      function updateResultsTable() {
        $.each(answersData, function (pitanje, podaci) {
          const srednjaVrednost =
            podaci.ukupnaOcena > 0
              ? (podaci.ukupnaOcena / podaci.brOdgovora).toFixed(2)
              : 0;

          $(`#prosecnaOcena${pitanje.slice(-1)}`).text(srednjaVrednost);

         /*starting from here, until the end of updateResults function*/
        const row = $(`#row${pitanje.slice(-1)}`);

          row.removeClass("bg-danger bg-warning bg-success");

          if (srednjaVrednost < 2.5) {
            row.addClass("bg-danger");
          } else if (srednjaVrednost >= 2.5 && srednjaVrednost <= 3.5) {
            row.addClass("bg-warning");
          } else {
            row.addClass("bg-success");
          }
        });
      }

      $("#pollForm button").on("click", function (event) {
        event.preventDefault();

        saveAnswers();
      });
    </script>

I tried writing script that will find out the average of the grades given by user and it all works except the background giving part.

GET data php , mySql

I’m working on a project, and there’s a products page with each product having an ID. When I click on the cart button, I want it to fetch me the product information including its name, image, and more. I’m a bit confused and I know I have a lot of errors. Can you help me?

solution

 <?php
include('../database.php');

$reserveren = isset($_GET['action']) ? $_GET['action'] : '';

if ($reserveren === 'get_data') {
    $stmt = $conn->prepare("SELECT GROEP.naam AS groep_naam, MERK.naam AS merk_naam, PRODUCT.opmerkingen, BESCHRIJVING.naam AS beschrijving_naam, MIN(PRODUCT.datumBeschikbaar) AS datumBeschikbaar, COUNT(PRODUCT.product_id) AS aantal_beschikbare_producten, IMAGE.image_data
    FROM GROEP
    INNER JOIN MERK ON GROEP.merk_id_fk = MERK.merk_id
    INNER JOIN PRODUCT ON GROEP.groep_id = PRODUCT.groep_id
    INNER JOIN BESCHRIJVING ON GROEP.beschrijving_id_fk = BESCHRIJVING.besch_id
    INNER JOIN IMAGE ON GROEP.image_id_fk = IMAGE.image_id
    WHERE PRODUCT.zichtbaar = true AND PRODUCT.isUitgeleend = false
    GROUP BY GROEP.naam, MERK.naam, PRODUCT.opmerkingen, BESCHRIJVING.naam, IMAGE.image_data");

    $stmt->execute();

    $result = $stmt->get_result();

    $data = [];
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
    }

    $stmt->close();

    echo json_encode($data);
}
?> 

How to render right buttons (Like or Unlike) in a post based on user’s choice using Javascript in a web app?

I’m working on a web app where a user has the option to like or unlike a post posted by another user. I created a button and wrote a Javascript function to change the text inside the button based on user’s choice. If user clicks Like button it changes to Unlike and vice versa.

Here’s my code:

models.py

class Post(models.Model):
    """ Model representing a post. """
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)
    no_of_likes = models.IntegerField(default=0)

    def __str__(self):
        return f"Post {self.id} by {self.user.username} on {self.timestamp}"
    
class Like(models.Model):
    """ Model representing a like. """
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.user} likes {self.post}"

urls.py

path("", views.index, name="index"),
path("like/<int:post_id>", views.like, name="like"),
path("unlike/<int:post_id>", views.unlike, name="unlike"),

views.py

def index(request):
    """ Home page. """
    posts = Post.objects.all().order_by('-timestamp')
    paginator = Paginator(posts, 5)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    likes = Like.objects.all()
    
    # List of post ids.
    liked_posts = Like.objects.filter(user=request.user).values_list('post', flat=True)
    liked_posts = list(liked_posts)
    
    return render(request, "network/index.html", {
        "posts": posts,
        "page_obj": page_obj,
        "likes": likes,
        "liked_posts": liked_posts,              
    })

@login_required
def like(request, post_id):
    
    post = Post.objects.get(pk=post_id)
    user = User.objects.get(pk=request.user.id)
    like = Like.objects.create(user=user, post=post)
    like.save()
    
    post.no_of_likes = Like.objects.filter(post=post).count()
    post.save()
    return JsonResponse({"message": "successfully liked", "no_of_likes": post.no_of_likes})

@login_required   
def unlike(request, post_id):
    
    post = Post.objects.get(pk=post_id)
    user = User.objects.get(pk=request.user.id)
    like = Like.objects.filter(user=user, post=post)
    like.delete()

    post.no_of_likes = Like.objects.filter(post=post).count()
    post.save()
    return JsonResponse({"message": "successfully unliked", "no_of_likes": post.no_of_likes})

index.html with Javascript

<!--Create button-->
<button type="button" class="btn btn-success like" id="like{{ post.id }}" onclick="toggleLike('{{ post.id }}')">Like</button>

// JavaScript
    function toggleLike(postId) {
        var likeButton = document.getElementById('like' + postId);

        if (likeButton.innerText === 'Like') {
            // Change button to Unlike
            likeButton.innerText = 'Unlike';
            likeButton.style.background = '#dc3545'; // Change button color to red
            // Update counter
            fetch(`/like/${postId}`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRFToken": "{{ csrf_token }}",
                },
            })
            .then(response => response.json())
            .then(data => {
                document.querySelector("#no-of-likes" + postId ).innerHTML = data.no_of_likes + " likes";
            })
        } else {
            // Change button to Like
            likeButton.innerText = 'Like';
            likeButton.style.background = ''; // Reset button color
            // Update counter
            fetch(`/unlike/${postId}`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRFToken": "{{ csrf_token }}",
                },
            })
            .then(response => response.json())
            .then(data => {
                document.querySelector("#no-of-likes" + postId).innerHTML = data.no_of_likes + " likes";
            })
        }
    }

When I refresh the page all buttons are changing to Like even though user liked some posts where it should display Unlike buttons.

I tried to fix this by writing following code but it didn’t resolve the issue.

document.addEventListener('DOMContentLoaded', function() {
        const buttons = document.querySelectorAll(".like");
         
        buttons.forEach(button => {
            const postId = button.getAttribute('id').replace('like', '');
            
            if ('{{ liked_posts }}'.includes(postId)) {
                button.innerText = "Unlike";
                button.style.background = "red";
            } else {
                button.innerText = "Like";
                button.style.background = "green";
            }            
        });
    })

With this new code I’m getting a weird bug where if I liked only Post No. 12 by one other user, Post Nos. 1 and 2 by this same other user are also showing Unlike buttons. And if I like Post No. 11 by this other user, Post No. 1 also displaying Unlike button. I think this is something to do with .include() function but I can’t figure out the issue. Any suggestions on how to fix this bug? Thanks in advance!