Can a django formset that dynamically adds fields have persistent data?
I've had trouble with dynamically adding fields in Django before and this stackoverflow question helped me: dynamically add field to a form
To be honest, I'm not entirely sure what you mean by "persistent" in your case - are the values of your forms being removed as you add inputs? Are you sure it isn't something with your JS?
A coworker of mine finally figured it out. Here is the revised views.py:
from django.shortcuts import render
from django.http import HttpResponse
from form import ModelForm, Parent
from models import Form, ParentForm, Contact
from django.http import HttpResponseRedirect
from django.forms.formsets import formset_factory
def create(request):
ParentFormSet = formset_factory(Parent, extra=1)
boolean = False
if request.POST:
Parent_formset = ParentFormSet(request.POST, prefix='Parent_or_Third_Party_Name')
if 'add' in request.POST:
boolean = True
list=[]
for i in range(0,int(Parent_formset.data['Parent_or_Third_Party_Name-TOTAL_FORMS'])):
list.append({'name': Parent_formset.data['Parent_or_Third_Party_Name-%s-name' % (i)], 'Relation': Parent_formset.data['Parent_or_Third_Party_Name-%s-Relation' % (i)]})
Parent_formset = ParentFormSet(prefix='Parent_or_Third_Party_Name', initial= list)
form = ModelForm(request.POST)
if form.is_valid() and Parent_formset.is_valid():
form_instance = form.save()
for f in Parent_formset:
if f.clean():
(contobj, created) = Contact.objects.get_or_create(name=f.cleaned_data['name'])
(obj, created) = ParentForm.objects.get_or_create(student_name=form_instance, name=contobj, Relation=f.cleaned_data['Relation'])
return HttpResponseRedirect('http://Google.com')
else:
form = ModelForm()
Parent_formset = ParentFormSet(prefix='Parent_or_Third_Party_Name')
return render(request, 'content/design.html', {'form': form, 'Parent_formset': Parent_formset, 'boolean':boolean})
def submitted(request):
return render(request, 'content/design.html')
Thank you for your input, those of you who answered :)
I was once trying to do something like this, and was directed to django-crispy-forms by a man much wiser than I. I never finished the project so I can't offer more help than that, but it could be a starting point.