Lizzeiy
Lizzeiy

Reputation: 426

Django - Add field to form dynamically

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 %}

Upvotes: 5

Views: 8636

Answers (1)

CODEkid
CODEkid

Reputation: 250

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)

Upvotes: 7

Related Questions