"Implement a feature to insert Django forms dynamically on a webpage by simply clicking a

Hey there! I'm currently working on a form where I want a new form to appear below the existing one when I click the "+" button. Let's say I have a form for entering a name:

VoteType
name: [        ]
{+}  -- (button)

Once I click "+", the form should expand like this:

VoteType
name: [        ]

Vote1 name [        ]
      image [        ]
      date [        ]

{+} -- (button)

I would like to keep adding more "Votes" by clicking the "+" button as many times as needed.

I've been searching for solutions to implement this but haven't found the right one yet.

This is the current 'createview' in my 'views.py':

def create(request):
    voteTypeForm = VoteTypeForm(request.POST or None)
    voteForm = VoteType(request.POST or None)
    clicked = 0
    instance = voteTypeForm.save(commit=False)
    instance.pub_date = timezone.now()
    instance.save()
    
    context = RequestContext(request,{
            'voteTypeForm': voteTypeForm,
            'clicked': clicked,
            'voteForm': voteForm,
    })
    return render(request, 'Vote/create.html', context)

I am struggling with changing the value of 'clicked' variable in my views from the template. How can I use the button to update the 'clicked' value? If you have any better ideas or solutions, please feel free to share. I was advised that this might be more of a javascript issue rather than a Django one. So, I tried to modify the 'create.html' code by adding some javascript (source: here):

<form method='POST' action=''>{% csrf_token %}
    {{ voteTypeForm }}
    <input type='submit' value="create"/>
</form>
<fieldset id="fieldset">
    <legend id="legend">Voting Candidates</legend>
    <div id="placeholder">
        <form method='POST' action=''>{% csrf_token %}
            {{ voteForm }}
        </form>
    </div> 
    <p><button type="button" name="Submit" onclick="Add();">+</button></p>
</fieldset>
<script>
    var _counter = 0;
    function Add() {
        _counter++;
        var oClone = document.getElementById("template").cloneNode(true);
        oClone.id += (_counter + "");
        document.getElementById("placeholder").appendChild(oClone);
    }
</script>

However, even this code doesn't seem to work for me. Since I'm not very familiar with javascript, I'm having trouble identifying the issue. Can you provide some guidance on how to fix this code?

Answer №1

When faced with a similar requirement, I found myself making adjustments to a tutorial on underscore.js.

Another user shared their experience utilizing the same tutorial but opting out of using underscore here.

Both resources are quite detailed, so I won't be duplicating any content here.

Regardless, it is essential to make use of an inlineformset_factory (documentation here) in all instances to allow for saving multiple form instances.

Answer №2

Encountered multiple issues in this scenario.

The primary problem was mistakenly referencing VoteType instead of VoteForm in views, causing disruptions. Upon rectifying this error, encountered difficulty in accurately displaying forms with the correct number sequence. Rather than having the first form displayed directly in HTML, preferred to store it within JavaScript. Seeking assistance for these challenges on my second inquiry. The complete code solution will be provided there.

To address this question, simply a matter of mistakingly using VoteType instead of VoteForm.

After modifying the code and incorporating additional elements, the solution now looks like this.

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

Unusual quirks in javascript variables when used with arrays

Unsure if this question has been asked previously. Nevertheless, I couldn't find it anywhere. I've observed a peculiar behavior that seems to occur only with arrays. Here is the typical behavior I anticipate from variables: var k = 10, m = ...

Step-by-step guide for building and populating a JavaScript Dictionary

Does anyone know how to create a Dictionary with a key and a list of values pair in Python? I have been able to create dictionaries with a single value for each key, but now I need to store multiple items as values for each key. Here is what I have tried: ...

Popunders are activated on their own accord

I've been working on a code that inserts a popunder into all the links on my page, but I'm struggling to make it run automatically without the need for a click. I've tried several approaches without success. Can anyone lend a hand? window. ...

Preventing Page Content Overflow in Semantic-ui SideNav

I am currently working on a webpage that includes a side navigation bar. I recently started using semantic-ui and its grid system, but I'm facing an issue where the content of the page flows under the side nav and gets hidden. I have tried various sol ...

The attribute 'name' does not exist for objects of type 'NoneType'

I'm currently in the process of developing a wine recommendation system. While working on the reviews/view.py page, I encountered the following error: 'NoneType' object has no attribute 'name' This specific line triggered the err ...

"Triggering a key press event for a selected item in a single

Is there a way to automatically add the selected value when the enter key is pressed on a chosen jQuery single select? I am looking for an event similar to keypress that can be used to trigger an action when the return key is pressed. <select id="mys ...

Is there a way to automatically disable a text field upon checking a checkbox?

I am looking for a way to automatically disable the division when the checkbox is clicked. If the current address matches the permanent address, I want the user to simply check the box to disable the fields for the permanent address. Thank you! <div ...

What is the best way to input data into this object using node.js?

When initiating a socket on the client side, the following message will be sent out: socket.onopen = function(event) { var jsonstring = JSON.stringify({"type":"join", "id":myStorage.username}); socket.send(jsonstring); }; On the server side, there ex ...

Struggling to configure Velocity Js?

After attempting to use Velocity Js for the first time, I encountered some issues while trying to create a navigation menu. Despite having functioning code and animations, the menu failed to open. I followed the instructions on the Velocity JS site by incl ...

connecting with Google Analytics

We are looking to incorporate Google Analytics into a sizable .NET website. The website utilizes multiple master pages (4 or 5), so the plan was to insert the necessary JavaScript code into each master page. <script type="text/javascript">//<![CD ...

Limiting input to specific characters is effective on Chrome, but unfortunately does not function on Firefox

This code snippet is designed to restrict user input to lowercase letters from a-z, numbers from 0-9, and the dash character "-". While it functions correctly in Chrome, it does not allow any input in Firefox. What could be causing this issue? $('#sl ...

"Displaying Undefined Content when an Incorrect Value is Added, but functioning correctly with the right

I am attempting to populate the HTML table below with data from a JSON file: When I set var i = "0";, I receive undefined, but changing it to var i = "dv"; results in nothing being displayed. I am uncertain of the error I am making and what is causing th ...

Is it more efficient to have a single global event listener or multiple event listeners of the same type in each component for productivity?

This particular mixin is a key component in numerous pages, often appearing in multiple sections within the page. data: () => ({ device: { mobile: false, tablet: false, tabletLand: false, notepad: false deskto ...

Customizing Bootstrap Styles in Angular: How to Override Specific Classes

Looking to customize an HTML element <div [style.color]="themeService.backgroundColor" class="col-md-10 col-md-offset-1 col-sm-10 col-sm-offset-1 col-lg-10 col-lg-offset-1"> <ul class="pagination" id="pag-bar"> <l ...

ERROR: Expo TaskManager Notifications [TypeError: Attempting to call an undefined function (near '...Notifications.presentLocalNotificationAsync...')]

I'm currently trying to figure out how to send notifications whenever a task is triggered, but I keep encountering an error that I can't seem to fix. Here's the error message: TaskManager: Task "background-fetch" failed:, [TypeError: unde ...

Having trouble preventing the scroll from moving even after setting body overflow to hidden in Next Js

I'm encountering an issue with my Nextjs project where I can't seem to prevent the page from scrolling even after using document.body.style.overflow set to hidden. Here is the code snippet: Code Sandbox Link Upon examining the code: In lines 11 ...

Generate a dynamic key object in Angular/TypeScript

I am working with an object called "config" and an id named "id". My goal is to create an array of objects structured like this: [ "id" : { "config1: ... "config2: ... "config3: ... } "id2" : { "config ...

Displaying the value in Angular without triggering a change

How can I display the initial value of a variable without updating it when the value changes? <span>{{value}}</span> I want the span to only show the initial value and not update when the value changes. Is there a way to accomplish this? ...

Function for emptying the cart and Webstorage in JSON format

Currently, I am working on a university project to develop a website for a company looking to sell products online. While creating the shopping cart functionality, I encountered some challenges but managed to implement a 'drag and drop' feature s ...

Incorporating new elements onto the page without causing the existing elements to re-render

My challenge involves working with a large array of objects, where each object corresponds to one element. To display these elements on the page, I utilize the map() function, but currently only the first 5 elements are being rendered initially. In order t ...