5

Objective: Add a field to a form dynamically by pressing a button. Once submitted, store those values from all the fields in a list.

(I have already looked at other questions on Stack Overflow and tried to find a basic tutorial/explanation how to do this: dynamically add field to a form)

I am not sure what I need to be looking up/researching. I understand it will involve JavaScript but its the Django side that I am unsure how it will work.

I have created a basic form for starters:

enter image description here

Models.py

from django.db import models

class SimpleForm(models.Model):
    basic_field = models.CharField(max_length=200)

Forms.py

from django import forms
from models import SimpleForm

class SimpleForm(forms.ModelForm):

class Meta:
    model = SimpleForm
    fields = ['basic_field']

Views.py

from django.shortcuts import render
from forms import SimpleForm

def index(request):
    if request.method == "POST":
        # For loop to iterate over dynamically created fields
        # Store values in list
    else:
        form = SimpleForm()
    return render(request, "index.html", {'form':form})

Index.html

{% block content %}
    <h1>Simple Form</h1>
    <form method="POST" class="post-form">{% csrf_token %}
        {{ form.as_p }}
        <button type="button" class="btn-default">Add Another Field</button>
        <button type="submit" class="btn-default">Submit</button>
    </form>
{% endblock %}
Community
  • 1
  • 1
Lizzeiy
  • 428
  • 1
  • 8
  • 22
  • 1
    Use jQuery or javascript to add fields to the form (you could give them all a common class name). On clicking submit, capture the event in your own event handler, prevent the default action and convert values from all your fields into a list or JSON object. Pass this to your server and everything else is business as usual! – rohithpr Aug 25 '15 at 01:52
  • Heres a question where the god himself has answered http://stackoverflow.com/questions/2942359/adding-fields-to-django-form-dynamically-and-cleanly – e4c5 Aug 25 '15 at 05:47

1 Answers1

7

Try using django-formsets. You can start with this neat tutorial.

Basically ,what you need to do is create a formset out of your forms in your views.py.

    from django.forms.formsets import formset_factory
    CompoundFormset = formset_factory(SimpleForm,max_num=10,extra=1)
CODEkid
  • 240
  • 4
  • 8