Is there a way to access the edit section without having to reload the page for every post in Django using Javascript?

This snippet represents my HTML template:

<div class="posts">
  <h3> <a href ="{% url 'profile' p.user.id %}"> {{p.user}}: </a> </h3> <p>{{p.timestamp}}</p>
    <br>
<p><i class="fas fa-heart"></i> {{ p.likes.count }}</p>
<p style="text-align: center;"> {{ p.post }} </p> 
{% if p.user.id == user.id %}
<button class="btn btn-primary edit" style="display: inline;">Edit</button><hr></div>
<div id="editsec">
<textarea rows=6 cols=100 style="opacity: 0.7;">{{p.post}} </textarea>
<form action=""><button class="btn btn-success">Save</button></form>
 </div>
 {% endif %}  
   {% endfor %}

Within the CSS, I've hidden the editsec section so that it only appears when a user clicks on the edit button. Here is the corresponding JavaScript code:

      document.addEventListener('DOMContentLoaded', function() {
var edit = document.getElementsByClassName('edit')
for (var i = 0 ; i < edit.length; i++) {
edit[i].addEventListener('click', () => {
    document.getElementById('editsec').style.display = "block"; 
    document.querySelector('.posts').style.display = "none"; 
});
  }
 });  

However, when there are multiple posts on the homepage and I click on an edit button for a post, it still displays the editsec section of the first post. I attempted to make editsec a class by implementing the following:

document.addEventListener('DOMContentLoaded', function() {
var edit = document.getElementsByClassName('edit')
var editsec = document.getElementsByClassname('editsec')
for (var i = 0 ; i < edit.length; i++) {
edit[i].addEventListener('click', () => {
   for (var a = 0 ; a < edit.length; a++) {
    editsec[a].style.display = "block"; 
    document.querySelector('.posts').style.display = "none"; 
   }
});
  }
 });  

Now, clicking on one edit button displays all editsec sections. How can I modify it to show only the respective post's edit section?

Answer №1

To create dynamic content, avoid placing it within the template and instead incorporate it into your JavaScript code.

Instead of rendering the template in views.py, I suggest 1) returning a JSON response of posts.

2) Use your JavaScript code to fetch the post data and generate an element for displaying posts. Then insert it into your template using the following method:

document.querySelector(".posts").innerHTML = data

3) Next, include your edit section like this:

const bigsection = document.createElement('div');
bigsection.id = `button-div-${post.id}`;
// Hide this section until the user clicks the edit button
const editsec = document.createElement('div');
editsec.style.display = 'none';
editsec.id = `edit-div-${post.id}`; // Assign unique IDs to each section accordingly.
let form = `<textarea class="form-control" id="content-${post.id}" name="post_content">`
+ `${post.content}</textarea>`;
editsec.innerHTML = form; // Update the contents of your div

Add your button to an event listener so that when the user clicks on it, the dynamic content is displayed.

Answer №2

When I encountered this issue while creating a posting website, I found a helpful solution that worked well for me.

The key is to assign both the button and edit div an ID using data-id="{{p.id}}". Then, in your JavaScript code, retrieve the button dataset.id and only display the div if the button dataset.id matches the div dataset.id.

By the way, if you're working on CS50 Web, there's a project similar to this task. You can check out my version here.

If you're not already enrolled in CS50 Web, I highly recommend it. You can find more information about the course here. It's a fantastic offering from Harvard University.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are alternative ways to communicate with the backend in Backbone without relying on model.save()?

Is there a more effective method to communicate with my backend (node.js/express.js) from backbone without relying on the .save() method associated with the model? Essentially, I am looking to validate a user's input on the server side and only procee ...

Is there a way to block form submissions for users who have disabled JavaScript?

Our inquiry form mandates users to input basic information such as their name, location, contact details, and a comment or question. Unfortunately, we have been receiving numerous incomplete forms where essential fields are left blank. It has come to our ...

Is it possible to impose a different style on an element from another culture?

I am currently developing a themes library along with a demo page. The challenge I'm facing is that the demo page needs to showcase styles from the library without using all of the elements. For instance, consider the following style in an external s ...

Incorporating input utilities into a text field

Currently working on a Django blog website catering to bloggers who are not well-versed with Markdown/Markup. I am considering incorporating these tools into my textarea, as shown in the image below: https://i.sstatic.net/ud4hV.jpg Any recommendations on ...

Sort through a list of items by the key input when characters are removed from the input field, ensuring that the color remains constant

<ul class="locationlist list-unstyled"> <li> <div class="checkbox checkbox-success"> <input id="checkbox1" type="checkbox"> <label for="checkbox1"> Vijayanagar </label> </div> </li> <li> <div class=" ...

Issue with Tweening in Three.js: Initial value does not change

Having trouble with tweening my camera position. I've set up a Codepen with minimal code to showcase the issue, complete with annotations and plenty of console.log() statements for debugging purposes. Check out the Codepen The starting point of my c ...

Creating a dynamic page footer for a PDF document using Rotativa's content generation capabilities

As I work on generating a PDF, my employer has requested that I add a footer to each page of the document. Currently, the PDF is being created using Rotativa, where an HTML page is converted into a PDF. However, I am facing a challenge in determining the ...

Have developers created an event trigger for when google maps controls finish loading?

While I am aware of the tilesloaded event, it appears that the controls load after this event. My goal is to use jQuery to retrieve the controls, but I am struggling to identify the appropriate event to listen for. ...

Calculating the Distance Between Elements within a Flex Container Using JavaScript

I am looking to calculate the margin left and right for children of a flex item <div class="sec images" style="display:flex;justify-content:space-between"> <img src="images/en_mb-mega-01.png" alt=""> ...

The PKIJS digital signature does not align with the verification process

Explore the code snippet below const data = await Deno.readFile("./README.md"); const certificate = (await loadPEM("./playground/domain.pem"))[0] as Certificate; const privateKey = (await loadPEM("./playground/domain-pk ...

The member 'email' is not found in the promise type 'KindeUser | null'

I'm currently developing a chat feature that includes PDF document integration, using '@kinde-oss/kinde-auth-nextjs/server' for authentication. When trying to retrieve the 'email' property from the user object obtained through &apo ...

What is the best way to eliminate the border from a dropdown menu in bootstrap?

After copying and pasting a dropdown menu from bootstrap, I decided to experiment with it. Initially, I used the dropdown as a button, but then switched it to anchor tags. However, when I made this change, unwanted borders suddenly appeared and no matter w ...

Using React.js and mdbottstrap to display a Modal when clicking

I'm struggling to get a modal to open with a click on my page. The button is there, but clicking it doesn't trigger the modal to appear. I've been searching for a solution without any luck so far. function ModalPage(props) { const [usern ...

Django and Coleman - A Dynamic Duo

Hi there! I am new to Django and currently working on a project involving a shopping cart/e-commerce solution. I've been diving into the Django 1.2 e-commerce book by Jesse Legg, and I'm hoping to connect with someone who has experience with it. ...

Error messages are being generated by Angular CLI due to an unclosed string causing issues with the

After incorporating styles from a Bootstrap theme into my Angular 8 project and updating angular.json, I encountered a compile error displaying the following message: (7733:13) Unclosed string 7731 | } 7732 | .accordion_wrapper .panel .panel-heading ...

What is the process for setting a linear gradient border color on a table row's border?

Currently, I am attempting to apply a linear gradient border color to the table row. Below are the codes for the table: td:first-child { border-left: 1px solid black; border-bottom-left-radius: 50px; border-top-left-radius: 50px; } td:last-child { bor ...

How to Update ManyToMany Relationships in DRF Serializer's update() Method

Exploring the Model: class Dvd(models.Model): movie = models.ForeignKey(Movie) price = models.DecimalField(...) sold_copies = models.IntegerField(...) final_value = models.DecimalField(...) class Licence(models.Model): distribution = ...

Warning: Unhandled promise rejection - The type error occurred because the property 'close' of the object is undefined

I am currently configuring node.js in order to test my JavaScript codes using the Jest JavaScript testing framework. Can anyone spot what I might have done incorrectly? package.json file { "name": "institute-jest", "version&quo ...

How to retrieve the content of <p> elements by their id or class in PHP

I am currently utilizing a Script that enables the display of URL content within the meta tag "description". This script utilizes PHP in the following manner: $tags = get_meta_tags($url); Subsequently, it is called like so: <label class="desc"> ...

Icon appearing outside the button instead of inside

Here's a button I'm working with: <button class="glyphicon glyphicon-option-horizontal" (click)="myFuncion()"></button> Recently, I updated my bootstrap library from version 3 to 4.2.1 and now the icon is no longer visible. I' ...