我正在尝试在django中保存一个formset。 为此,我有我的模型和自定义表单。 然后我以这种方式创建我的formset:
QuoteFormSet = formset_factory(QuoteForm, extra=2)
formset = QuoteFormset(request.POST)
但是当我执行formset.save()时,我得到AttributeError: 'QuoteFormFormSet' object has no attribute 'save'
我的模特:
class Quote(models.Model):
country = models.CharField(max_length=2,)
street = models.CharField(max_length=100,)
我的表格:
class QuoteForm(forms.ModelForm):
class Meta:
model = Quote
country = forms.ChoiceField(choices=COUNTRIES, required=False)
street = forms.CharField(max_length=100, required=False)
答案 0 :(得分:8)
好的,我必须使用modelformset
代替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,
})
答案 1 :(得分:1)
您没有实例化formset。
formset = QuoteFormset(request.POST)
答案 2 :(得分:-1)
Formset没有保存属性。因此,尝试逐个保存formset中的表单对象。它会起作用。
if formset.is_valid():
formset = QuoteFormset(request.POST)
for form in formset:
form.save()