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 %}
2
  • 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! Commented Aug 25, 2015 at 1:52
  • Heres a question where the god himself has answered stackoverflow.com/questions/2942359/… Commented Aug 25, 2015 at 5:47

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.