Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save a formset of custom forms django

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)
like image 869
maazza Avatar asked Dec 12 '22 15:12

maazza


1 Answers

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,
    })
like image 125
maazza Avatar answered Dec 22 '22 17:12

maazza