Save a formset of custom forms django
Asked Answered
S

3

5

I am trying to save a formset in django. To do so I have my model and a customized form. Then I create my formset this way :

QuoteFormSet = formset_factory(QuoteForm, extra=2)
formset = QuoteFormset(request.POST)

But when I do formset.save() i get AttributeError: 'QuoteFormFormSet' object has no attribute 'save'

my model :

class Quote(models.Model):
    country = models.CharField(max_length=2,)
    street = models.CharField(max_length=100,)

My form:

class QuoteForm(forms.ModelForm):
    class Meta:
        model = Quote
    country = forms.ChoiceField(choices=COUNTRIES, required=False)
    street = forms.CharField(max_length=100, required=False)
Separation answered 16/4, 2013 at 15:3 Comment(0)
S
12

Ok I had to use modelformset instead of formset

from django.forms.models import modelformset_factory

def new_quote(request):
    QuoteFormSet = modelformset_factory(Quote, form=QuoteForm, extra=2)
    if request.method == 'POST':
        formset = QuoteFormSet(request.POST, request.FILES)
        if formset.is_valid():
            formset.save()
            #
            return HttpResponseRedirect('/')
    else:
        formset = QuoteFormSet()

    return render(request, 'request_quote_form.html', {
    'formset': formset,
    })
Separation answered 17/4, 2013 at 8:9 Comment(0)
D
1

You didn't instantiate the formset.

formset = QuoteFormset(request.POST) 
Dawdle answered 16/4, 2013 at 15:11 Comment(1)
i did it but forgot to add it to my post >_<Separation
L
1

Formset has no attribute as save. So, try saving form objects in formset one by one. It will work.

if formset.is_valid():
    formset = QuoteFormset(request.POST) 
    for form in formset:
       form.save()
Lunt answered 16/2, 2016 at 14:36 Comment(1)
However, this will save also forms of the formset that have been marked for deletion.Spank

© 2022 - 2024 — McMap. All rights reserved.