Add and Remove Form Fields in Django with jQuery

To dynamically add or remove multiple input fields in a Django form using jQuery, you’ll need to combine Django form handling with JavaScript for the front-end functionality. Here’s a step-by-step guide to achieve this:

Django Setup

First, ensure you have a Django form that you want to dynamically add or remove fields to. Let’s assume you have a Django model and a corresponding form.

models.py:

from django.db import models

class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()

forms.py:

from django import forms
from .models import Item

class ItemForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = ['name', 'description']

views.py:

from django.shortcuts import render
from .forms import ItemForm

def item_view(request):
    form = ItemForm()
    return render(request, 'item_template.html', {'form': form})

HTML and jQuery

You’ll need to create an HTML template with jQuery to handle the dynamic addition and removal of input fields.

item_template.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dynamic Form Fields</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .form-group { margin-bottom: 10px; }
        .remove-btn { cursor: pointer; color: red; }
    </style>
</head>
<body>
    <form method="post" action="">
        {% csrf_token %}
        <div id="form-container">
            <!-- Dynamically added fields will go here -->
        </div>
        <button type="button" id="add-field-btn">Add Field</button>
        <button type="submit">Submit</button>
    </form>

    <script>
        $(document).ready(function() {
            let fieldCount = 0;

            // Function to add new fields
            function addField() {
                fieldCount++;
                let newField = `
                    <div class="form-group" id="field-group-${fieldCount}">
                        <input type="text" name="field_${fieldCount}" placeholder="Field ${fieldCount}" />
                        <span class="remove-btn" data-id="${fieldCount}">Remove</span>
                    </div>
                `;
                $('#form-container').append(newField);
            }

            // Function to remove fields
            function removeField(fieldId) {
                $(`#field-group-${fieldId}`).remove();
            }

            // Add field button click event
            $('#add-field-btn').click(function() {
                addField();
            });

            // Remove field click event delegation
            $('#form-container').on('click', '.remove-btn', function() {
                let fieldId = $(this).data('id');
                removeField(fieldId);
            });
        });
    </script>
</body>
</html>

Handling Form Submission

To handle the dynamic fields on form submission, you will need to process these fields in your Django view. Assuming you’re using the same view as before:

views.py:

from django.shortcuts import render, redirect
from .forms import ItemForm

def item_view(request):
    if request.method == 'POST':
        # Process form data here
        form_data = request.POST
        # Do something with form_data, e.g., save to database
        # Example: You might loop through the fields and process them
        for key, value in form_data.items():
            if key.startswith('field_'):
                print(f"Field {key}: {value}")

        return redirect('success_url')  # Redirect after processing

    form = ItemForm()
    return render(request, 'item_template.html', {'form': form})