How do I add a Multilevel dropdown to a Django template?

I am trying to add a dropdown to my navbar in base.html that shows multiple categories from a store. Each of these categories has a sub-category associated with it. I’ve created a model in Django that maps this relationship like so.

models.py

class CategoryView(models.Model):
    parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank = True, null=True)
    title = models.CharField(max_length=100) 
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

And I’m passing this model to the template using context processors as so

def categoriesdropdown(request):
    catg = CategoryView.objects.filter(parent=None)
    context = {'catg':catg}    
    return context

Now I am trying to display these categories and sub-categories as a multilevel dropdown using bootstrap. I have tried implementing mostly all solutions from the answers here:

Bootstrap 4: Multilevel Dropdown Inside Navigation

Bootstrap dropdown sub menu missing

https://mdbootstrap.com/docs/standard/extended/dropdown-multilevel/

But nothing seems to work.

Below is the dropdown from my template.

base.html

<div class="nav-item dropdown">
    <a href="#" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="nav-link dropdown-toggle">Categories</a>
    <ul class="dropdown-menu dropdown-menu2" aria-labelledby="dropdownMenuLink">
    {% for category in catg %}
        <li class="dropdown-submenu">
            <a class="dropdown-item dropdown-toggle" href="#" id="multilevelDropdownMenu1" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">{{ category.title }}</a>
            <ul class="dropdown-menu2" aria-labelledby="multilevelDropdownMenu1">
                {% for subcategory in category.children.all %}
                    <li><a href="#" class="dropdown-item">{{ subcategory.title }}</a></li>
                {% endfor %}
            </ul>
        </li>
    {% endfor %}
</ul>

I can see that all the categories and sub-categories are listed properly in the dropdown, however my sub-categories appear right below the categories and not as a next level dropdown.

enter image description here

Note: The dropdown toggle appears as is and doesn’t work.

base.css

.dropdown-submenu {
    position: relative;
  }
  
.dropdown-submenu .dropdown-menu2 {
top: 10%;
left: 100%;
margin-top: -1px;
}
  
.navbar-nav li:hover > ul.dropdown-menu2 {
    display: block;
} 

How do I get the category toggles to work and only display the sub-categories when the toggle is clicked or hovered over?

How to create a custom fetch plugin with a method wrapper in Nuxt 3?

I’m migrating a Nuxt 2 application to Nuxt 3 (Vue2 to Vue3 as well) and I used to use Axios library in my old application but now Vue 3 has its own internal fetch to make HTTP requests so Axios library for Nuxt 3 is not supported anymore. I followed the documentation on how to create a custom fetch function and it’s working fine but I want to add a wrapper around it to make it work in a similar way as it used to with Axios. Currently I’m making my requests like this:

const resp = await useAPI(`/user/${url}`, {method: "POST", body: data})

I would like to call my composable like this:

const resp = await useAPI.post(`/user/${url}`, data, {/*any additional header*/})

I can’t grasp my head around how to wrap the plugin for it to work this way, here’s my customFetch plugin and my composable

customFetch plugin

export default defineNuxtPlugin((nuxtApp) => {

  const token = useCookie('token')

  const api = $fetch.create({
    baseURL: "http://localhost:3012",
    onRequest({ request, options, error }) {
      if (token.value) {
        const headers = options.headers ||= {}
        if (Array.isArray(headers)) {
          headers.push(['Authorization', `Bearer ${token.value}`])
        } else if (headers instanceof Headers) {
          headers.set('Authorization', `Bearer ${token.value}`)
        } else {
          headers.Authorization = `Bearer ${token.value}`
        }
      }
    },
    async onResponseError({ response }) {
      if (response.status === 401) {
        await nuxtApp.runWithContext(() => navigateTo('/login'))
      }
    }
  })

  // Expose to useNuxtApp().$api
  return {
    provide: {
      api
    }
  }
})

useAPI composable

import type { UseFetchOptions } from 'nuxt/app'

export function useAPI<T>(
  url: string | (() => string),
  options: UseFetchOptions<T> = {},
) {
  return useFetch(url, {
    ...options,
    $fetch: useNuxtApp().$api as any
  })
}

How to deploy a decoupled web application built with .NET Core (.NET 6) for Backend and vanilla html & javascript for Frontend to Azure?

I’ve built a simple web app using .Net Core (.Net 6) for the backend and vanilla html & javascript in a single “index.html” file in VS Code for the frontend. I’ve tested it on my local and everything works as intended.

I’m trying now to deploy it to Azure. I’ve deployed the backend successfully, but I’m not sure how to deploy the frontend. I know how to sign into Azure through VS Code and how to upload my “index.html” to Azure, but I don’t know how to make the two parts work together in Azure. I also don’t know if I should upload the index.html file into the same app service or a separate one.

I’ve searched here on Stack and also on the general Internet a lot for some info on this. Through this search, I’ve found basically two methods to do this. One is to upload the index.html as a “static” file and then make it communicate with my backend using Azure Messaging Service. The second is to use Docker to create a container that houses both the frontend and the backend and upload the container to Azure.

I would like to get some advice please?

I feed the mediaSource sourceBuffer with Uint8Arrays no errors but the video do not play. Why?

I have this web page (see code), the script runs without errors and the chunks are showed in the console as Uint8Arrays but the video do not show-up. On the server side the 13 .mp4 videos are present.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Video</title>
        <!--<link rel="stylesheet" href="styles.css">-->
    </head>
    <body>
        <div class="content">
            <h1>My Video</h1>
            <video id="video" width="640" height="480" type="video/mp4" autoplay muted decoration></video>
<script>
'use strict';

var video = document.querySelector('video');
var i = 0;
var url = "0.mp4";

if (!window.MediaSource) {
  alert('The MediaSource API is not available on this platform');
}

var mediaSource = new MediaSource();
var sourceBuffer;

video.src = window.URL.createObjectURL(mediaSource);

mediaSource.addEventListener('sourceopen', function() {
  sourceBuffer =
      mediaSource.addSourceBuffer('video/mp4'); // ; codecs="h264"
  get(url, MyCallback);
});

function MyCallback(chunk)
{
    console.log(chunk);
    sourceBuffer.appendBuffer(chunk);
    if (video.paused) {
        video.play(); // Start playing after 1st chunk is appended.
    }
    i++;
    if(i===14)
        i = 0;
    url = i.toString()+".mp4";
    get(url, MyCallback);
}

function get(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'arraybuffer';
  xhr.send();

  xhr.onload = function() {
    if (xhr.status !== 200) {
      alert('Unexpected status code ' + xhr.status + ' for ' + url);
      return false;
    }
    callback(new Uint8Array(xhr.response));
  };
}

</script>
</div>
</body>
</html>type here

I did try to set the video scr= one of those mp4 and it was playing correctly, just to say the mp4 format seems good for firefox.

How to disable anti developer tools? [closed]

In this website : click here
When I enable developer tools it kick me from the website.

I try to inspect code to learning about the web code and get knowledge about the coding

I have tried to press right click is not pressing
I tried to click F12 it kick me
I tried to open developer tools from “more tools” option but still kick me
I tried to disable JavaScript

Is there way to unblock it?

This was not helpful How to unblock the Developer tools

How to Validate an Old Password Against an Encrypted Password in React Native?

I am a computer science student working on a project with friends, handling the frontend. The submission deadline is today, and I’ve been struggling with a password issue for days.

I need to implement a feature where users can update their profile information only if the entered “old password” matches the existing password stored in their account. Before integrating with the backend, I simply checked if the two variables matched. However, after the integration, I realized the stored passwords are encrypted, and I need to figure out how to compare the entered password with the encrypted password.

I’ve tried using GPT and searching online, but since this is my first project, I’m feeling lost. I really need help.

<Frontend (React Native) Code>

const handleSave = async () => {
    // Password validation
    if (profile.newPassword.length < 10) {
        Alert.alert('Password Error', 'The password must be at least 10 characters long.');
        return;
    }

    if (profile.newPassword !== profile.confirmPassword) {
        Alert.alert('Password Error', 'The new password and the confirmed password do not match.');
        return;
    }

    try {
        const existingProfileData = await AsyncStorage.getItem('profile');
        const existingProfile = existingProfileData ? JSON.parse(existingProfileData) : {};

        // Validate old password
        if (existingProfile.password !== profile.oldPassword) {
            Alert.alert('Password Error', 'The old password is incorrect.');
            return;
        }

        await updateUserInfo();
        Alert.alert('Save Completed', 'Profile information has been saved.');
        navigation.goBack();
    } catch (error) {
        console.error('Profile save failed:', error);
    }
};

Backend (Spring) Code

@Transactional
public JoinRequestDTO editInfo(@AuthenticationPrincipal PrincipalDetails principalDetails, JoinRequestDTO joinRequestDTO, String currentPassword) {
    usersEntity user = userRepository.findByStudentId_StudentId(principalDetails.getUsername())
            .orElseThrow(() -> new UsernameNotFoundException("User not found."));

    // Validate if the entered current password matches the stored password
    if (passwordEncoder.matches(currentPassword, user.getPassword())) {
        // Update nickname, keep existing info if null
        if (joinRequestDTO.getUsersDTO().getNickName() != null && !joinRequestDTO.getUsersDTO().getNickName().isEmpty()) {
            user.setNickName(joinRequestDTO.getUsersDTO().getNickName());
        }

        // Update password
        if (joinRequestDTO.getUsersDTO().getPassword() != null && !joinRequestDTO.getUsersDTO().getPassword().isEmpty()) {
            user.setPassword(passwordEncoder.encode(joinRequestDTO.getUsersDTO().getPassword()));
        }
    }
    userRepository.save(user);
    return joinRequestDTO;
}

I’ve tried so many different things over the past few days that I can’t remember them all…

Cannot read properties of null for cookie consent

I’m trying to set a cookie notice on my site. Above code is giving me error: Cannot read properties of null.

document.addEventListener('DOMContentLoaded', function() {

     if (document.cookie.indexOf('accepted-cookie') == -1) {
         document.cookie='cookie_name=VALUE; path=/';
         ShowStuff('cookie-notice');
     }  else {
        document.cookie='cookie_name=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
        HideStuff('cookie-notice');
     }
}, false);

function ShowStuff(id) {
    if (document.getElementById(id).style.display == 'none')
    {
        document.getElementById(id).style.display = 'block';
        document.cookie='cookie_name=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
    }
}

function HideStuff(id) {
    if (document.getElementById(id).style.display != 'none')
    {
        document.getElementById(id).style.display = 'none';
        document.cookie='cookie_name=VALUE; path=/';
    }
}

How can I fix this error?

Closing Chrome browser does not fire pagehide

When a user closes chrome while logged in to my system, I want to save some stats in our db as if they had properly used the sign out link. I have it working when the user navigates away, or when the user closes ONE the tab of multiple open tabs but not when the user closes the entire browser. What am I missing?

I added a onpagehide event handler that uses navigator.sendBeacon to update my db.

When the user navigates away, or when the user closes ONE the tab of multiple open tabs, the event handler fires and updates the db.

But when the user closes the entire browser, the event does not fire so the db is not updated.

window.addEventListener('pagehide', function() {ProcessLogout();});

Align list items between multiple columns

I have a multiple column layout, each of those columns contains a list:

<div class="row">
  <div class="col">
    <ul>
      <li>..</li>
      <li>..</li>
    </ul>
  </div>
  <div class="col">
    <ul>
      <li>..</li>
      <li>..</li>
    </ul>
  </div>
  ...
</div>

The number of items in each list is the same, however the content of each list item is different (they may include variable content like textarea too). My task is to align list items between columns so that the list item #1 from the first column was on the same line visually with the list items #1 from the other columns, the list item #2 from the first column was on the same line with the list items #2 from the other columns, etc. This 100% resembles the table structure and I do understand I need to use one (or a grid system), however using columns is a must in this project and and cannot change that.

A CSS only solution would be ideal. However, since each list sits in a different container, I doubt there is one. Here is what I tried/thought of so far:

Resizer Solution

  1. Create an object that would store the height of each list item in all lists, find the tallest one for each “row”, then set it programmatically to the remaining list items from that row.

  2. Set up a ResizeObserver that would listen to changes to each list’s height and repeat the above step.

This solution works, however it’s definitely not ideal because the alignment doesn’t happen immediately, so there is a flash of unaligned list items on page load and whenever list item content changes. Also the more columns and list items I add to the page, the “heavier” it gets.

Content solution

This one is a bit crazy, but looks like a working solution too. The idea is that each list item contains content from all list items from the same “row” stacked upon each other, however has the items it doesn’t need to display hidden (with 0 opacity). Thus, the longest content will push the list item’s height down aligning it with the rest of the list items from the same “row”. Kinda like this:

section {
  display: grid;
  width: 3rem;
  background-color: green;
}

div {
  grid-row-start: 1;
  grid-column-start: 1;
}

div:first-child {
  opacity: 0;
}
<section>
  <div>Lorem ipsum dolot sit amet</div>
  <div>Lorem</div>
</section>

Downsides is that it’s going to be a mess content-wise, also I am going to have issues with content that has id’s and if at one point I’d want to make the width of columns different, this will break everything which I don’t want.

I’d appreciate to see other ideas if you faced similar issues.

Alternatives to the Bootstrap event ”hidden.bs.modal”

I have problems with importing bootstrap in my JS file so i need to find an alternative to the event “hidden.bs.modal”. I need it to use it just like in this W3school example

I also need to find an alternative to the event “shown.bs.modal”.

More precisely my code is:

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('deadpool').addEventListener('hidden.bs.modal', event => {
        document.getElementById('byebye').pause();
    });

    document.getElementById('deadpool').addEventListener('shown.bs.modal', event => {
        document.getElementById('byebye').play();
    });
});

where byebye is the id of an audio file and deadpool is the id of the modal.

How can I use a like counter for each blogpost

I have a blog in blogger and would like to add a like counter to each post. I know that each post ID is stored in data:post.id/ but don’t know how to retrieve that in the onclick function.

I tried to get the post id but always have to put it manually on the onlick=’likePost()’ function to get something stored in the database. How can I get the value stored in data:post.id/ dynamic?

<script>
// store the main Firebase URL
var firebaseURL = 'My-Project-URL/pages/id/';

// update the likeCounts shown in a <span> beside each blogpost
var postDivs = document.querySelectorAll('.post');

for (var i = 0; i < postDivs.length; i++) {

    var postID = postDivs[i].id;

    var numLikes = getLikeCount(postID);

}

// this function grabs the likeCount for a particular post from the Firebase
function getLikeCount(postID) {
 
    console.log('running getLikeCount for post ID:', postID);
    
    var thisPostRef = new Firebase(firebaseURL + postID + '/like-count/');
    
    thisPostRef.once('value', function(snapshot) {
        
        console.log( postID + ' value:', snapshot.val() );
        
        if ( snapshot.val() ) {
            
            console.log( postID + ' contains:', snapshot.val() );

            document.querySelector('#' + postID + ' .like-count').innerHTML = snapshot.val() + ' likes';
            
        } else {
            
            console.log( postID + '- no data in Firebase' );
            
            return 0;
        
        }
    
    });
    
}

function likePost(id) {

    console.log('running likePost() for post ID:', id);
    
    var postRef = new Firebase(firebaseURL + id);
    
    // get current number of likes here, so we can increment if any exist
    postRef.child('like-count').once('value', function(snapshot){
        
        console.log( 'snapshot.val():', snapshot.val() );
        
        var currentLikes = snapshot.val() ? snapshot.val() : 0;
        
        console.log( 'currentLikes:', currentLikes );
    
        postRef.update({
            
            'postID': id,
            'like-count': currentLikes + 1
            
            }, function(error) {
                
              if (error) {
                  
                console.log('Data could not be saved:' + error);
              
              } else {
              
                console.log('Data saved successfully');
              
              }
            
            });
            
        getLikeCount(id);
    
    });
    
}
</script>

Show the likes value:

<a expr:name='data:post.id'/> <button onclick='likePost()'> <i class='fa fa-thumbs-up' style='font-size:36px'/></button> <span id='likes'/>

Nextjs fetch received by different nestjs endpoint

I’m doing a simple fetch on an internal page (like a product page), using a slug (like ‘my-product’) in the body, and it stopped working properly.

By debuggin it with the help of postman, making the precise same request on Postman leads to a right behavior and response, which is server properly by the endpoint POST api/kondos/findBy , that looks like this:

enter image description here

On postman the request looks like this:

postman request OK

But the same request using fetch, on a server side page on my Nextjs app, is looking like this:

export async function getKondoBySlug(slug: string) {
try {
  const body = { slug };
  const response = await fetch(`${apiUrl}/kondo/findBy`, {
    method: "post",
    cache: "no-store",
    mode: "cors",
    headers: {
      //"Content-Type": "application/json",
      'Content-Type': 'application/x-www-form-urlencoded',
      'Accept': '*/*',
      'Accept-Encoding': 'gzip, deflate, br',
      'Connection': 'keep-alive'
    },
    body: JSON.stringify(body)
  });
  return await response.json();

} catch (error) {
  console.log('FETCH ERROR', error);
}

}

And this function it’s being propely called on my page at: /src/app/(singles)/(default)/single/[[..slug]]/page.tsx , like this:

enter code here

By debugging everything, I understand that the request is being wrongly received by the api endpoint GET api/kondos/findOne, that looks like this:

enter image description here

How come the same identical requests are received by different endpoints in the api ?

Split a Set-Cookie header with multiple cookies in react-native

I have a question exactly the same as the question here, but I use react-native and my string was saved on my local device came from axios header like this


cAxios.interceptors.response.use(
  async function (response) {

    const cookieHeaders = response.headers['set-cookie']
    await storeData('cookie', cookieHeaders)
    // code here...

    return response
  },
  function (error) {
    // code here...
  }
);

That means that I cant use the Headers Constructor as the accepted answer says.

I have a sting like this

cookie1=value, cookie2=value2; Expires=Thu, 06 Jul 2023 14:45:25 GMT; path=value5, express-token=value; path=value

same as the question mentioned, if I do string.split(', ') my string is split in 4:

  1. cookie1=value
  2. cookie2=value2; Expires=Thu
  3. 06 Jul 2023 14:45:25 GMT; path=value5
  4. express-token=value; path=value

While here is my expected result:

  1. cookie1=value
  2. cookie2=value2; Expires=Thu, 06 Jul 2023 14:45:25 GMT; path=value5
  3. express-token=value; path=value

is there a way to parse this to get the correct cookie values?

Youtube cards list horizontal mouse scrolling

World! I’m trying to create a horizontal list of youtube video (embed code) cards, which is supposed to be scrollable horizontaly. I’ve found here on stackoverflow some code examples which work when you try to scroll list of divs, but it doesn’t word for youtube cards

What i’ve tried:
JS:

 export function useHorizontalScroll() {
    const elRef = useRef();

    useEffect(() => {
        const el = elRef.current;

        if (el) {
            const onWheel = e => {
                if (e.deltaY === 0) return;
                e.preventDefault();
                el.scrollBy({
                    left: e.deltaY < 0 ? -800 : 800,
                    behavior: "smooth"
                });
            };
            
            el.addEventListener("wheel", onWheel);

            return () => el.removeEventListener("wheel", onWheel);
        }
    }, []);

    return elRef;
}
const Component = () => {
const scrollRef = useHorizontalScroll();

return (<>
<div className="video-container" ref={scrollRef}>
  <iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ?si=jPdhWK5lCy4XWCuW" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
<iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ?si=jPdhWK5lCy4XWCuW" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
<iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ?si=jPdhWK5lCy4XWCuW" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div>
<>);

This just doesn’t work when mouse is over youtube fragment, but it does when mouse is over “video-container” block.
I’ve tried to add event listeners to children of “el” in useHorizontalScroll, right before return, but it didn’t help me
What should i try? Thanks!

Is there any html to docx js libraries that is continuously maintained such as phpoffice/phpword [closed]

I’ve been searching for a while to find out if there is any JS library that handles HTML to Docx conversion such as PHPOffice/PHPWord, I did find “html-docx-js” and “html-to-docx” but it seems that it contains multiple issues and no longer maintained and webpack 5.0.1 does not support it anymore.

Any suggestions please
Thank you