django 模型表单集抛出错误:ModelFormOptions”对象没有属性“private_fields”

xqnpmsa8  于 2023-03-24  发布在  Go
关注(0)|答案(1)|浏览(148)

我试图在一个只有2个字段的模型中创建30个字段,我知道它可以使用formset完成,但在提交表单时不支持save()方法,所以我将其更改为:modelformset支持save()方法,但使用modelformset会在design.html中抛出一个错误:ModelFormOptions' object has no attribute 'private_fields'如何解决这个问题?

from .forms import ColumnForm
from django.forms import modelformset_factory

def design(request):
    ColumnFormSet = modelformset_factory(ColumnForm, fields = ('name', 'selec_type'), extra=30)
    formset = ColumnFormSet
    if request.method == 'POST':
        formset = ColumnFormSet(request.POST)
        if formset.is_valid():
            formset.save()
            return redirect('Home')
    else:
        formset = ColumnFormSet()
    return render (request, 'design.html', {'formset':formset})

forms.py:

from django import forms
from .models import Column

class ColumnForm(forms.ModelForm):
    class Meta:
        model = Column
        fields = ['name', 'selec_type']

模板:

<form method='post'>
    {% csrf_token %}
{{ formset.management_form}}
   {% for form in formset %}
        {{form.as_p}}
   {% endfor %}
<button type='submit'>Save<button/>
<form/>

Models.py:

class Type(models.Model):
    TYPE_OF_DATA = (
        ('Number', 'Number'),
        ('character', 'character'),
        ('check_box', 'check_box'),
        ('date', 'date'),
        ('image', 'image'),
             )
    data_type = models.CharField(max_length=1000, choices= TYPE_OF_DATA)

class Column(models.Model):
     name = models.CharField(max_length=100)
     selec_type = models.ForeignKey(Type, on_delete=CASCADE)
zu0ti5jz

zu0ti5jz1#

Modelfromset不支持我的forms.py文件中的表单类:
所以,我改变了我的观点:

ColumnFormSet = modelformset_factory(ColumnForm, fields = ('name', 'selec_type'), extra=30)

对此:
x一个一个一个一个x一个一个二个x

相关问题