James
James

Reputation: 197

Form's cleaned_data is empty but formset's cleaned_data isnt?

I am trying to use the String values from a CharField in each form of a formset, however for some reason the cleaned_data for each form always appeares empty while the formset's cleaned data is not. Here is the code from my views.py:

    TagsFormSet = formset_factory(TagsForm, formset=TagFormSet, extra=applicantQuery.count())
    if request.method == 'POST':
        tags_formset = TagsFormSet(request.POST, request.FILES, prefix='tags', applicants=applicantQuery)
        if tags_formset.is_valid():
            for tagForm in tags_formset.forms:
                tagForm.saveTags()

where my form looks like this:

class TagFormSet(BaseFormSet):

def __init__(self, *args, **kwargs):
    applicants = kwargs.pop('applicants')
    super(TagFormSet, self).__init__(*args, **kwargs)
    #after call to super, self.forms is populated with the forms

    #associating first form with first applicant, second form with second applicant and so on
    for index, form in enumerate(self.forms):
        form.applicant = applicants[index]

class TagsForm(forms.Form):
    tags = forms.CharField()
    def __init__(self, *args, **kwargs):
        super(TagsForm, self).__init__(*args, **kwargs)
        self.fields['tags'].required = False;

    def saveTags(self):
        Tag.objects.update(self.applicant, self.cleaned_data['tags'])  

As I've said before, the tags_formset.cleaned data contains the correct information as entered on the page, however the form's cleaned data is empty. This code gives me a KeyValue error saying 'tags' isn't in the cleaned data as it has nothing in it (error thrown in saveTags function).

Upvotes: 2

Views: 1142

Answers (1)

James
James

Reputation: 197

Ok I just figured out what is happening (wow i'm dumb). The error occurs because i made tags.required False but call saveTags reguardless of if that particular form had any inputted values. The simple fix was to check to see if the cleaned_data dict was empty:

if tags_formset.is_valid():
    for tagForm in tags_formset.forms:
        #check if cleaned_data is non-empty
        if tagForm.cleaned_data:
            tagForm.saveTags()

Upvotes: 1

Related Questions