所以,我试图保存模板集,但很难找到最好的方法!
到目前为止,我在下面尝试的工作,但它一直保存空记录!
如果我删除它,下次填写表单并提交时会再次添加。正确保存数据(我检查了管理员和数据库),但是这个空记录一直在添加,就像它自动一次生成空条目一样。 ..i假设 可能有问题,但是从我在Google周围看到的东西来看,我尝试过的东西似乎与我试图遵循的例子。 有时它会出现重复的cpf键错误,尽管条目是唯一的,尽管有错误,仍然保存到db。
处理保存表单集的最佳方法是什么?我一直在搜索,我已经阅读了django formset文档并尝试了不同的方法,但这是迄今为止唯一有效的方法!
我还有其他4个与用户通过一对一相关的表单集。
我正在使用普通表格并且它工作正常,然后我不得不改变为formset并且全部丢失了哈哈!
任何见解都表示赞赏!
编辑:我刚刚意识到它在保存到数据库时跳了2个id,比如1 - 3 - 5 ......我想它确实是重复但只保存一个条目?
views.py
UserFormSet = formset_factory(UserForm)
if request.method == 'POST':
formset = UserFormSet(request.POST)
if formset.is_valid():
for form in formset:
if form.is_valid():
form.save()

forms.py
class UserForm(forms.ModelForm):
name = forms.CharField(
label="Nome completo",
required = True,
)
bdate = forms.CharField(
label="Data de nascimento",
required = True,
)
gender = forms.ChoiceField (
label="Sexo",
required = True,
choices = gender_choice,
)
cpf = forms.CharField(
label="CPF",
required=True,
max_length=14,
)
oab = forms.CharField(
label="OAB",
required=True,
)
phone = forms.CharField(
label="Telefone",
required=True,
)
email = forms.EmailField(
label="E-mail",
required=True,
widget = forms.TextInput()
)
class Meta:
model = User

models.py
class User(models.Model):
name = models.CharField(max_length=100, verbose_name='Nome Completo')
bdate = models.CharField(max_length=10, verbose_name='Data de Nasc.')
gender = models.CharField(max_length=15, verbose_name='Sexo')
cpf = models.CharField(max_length=14, unique=True, verbose_name='CPF')
oab = models.CharField(max_length=15, unique=True, verbose_name='OAB')
phone = models.CharField(max_length=15, verbose_name='Celular')
email = models.EmailField(max_length=50, verbose_name='E-mail')
def __unicode__(self):
return self.name
class Meta:
verbose_name = u'Identificação'
verbose_name_plural = u'Identificação'

curriculo.html
<form ...>
<h3>Dados de Identificação</h3>
{{ UserFormSet.management_form }}
{% for form in UserFormSet %}
<label>Nome completo:</label>
{{ form.name }}
<label>Data de nascimento:</label>
{{ form.bdate }}
<label>Sexo:</label>
{{ form.gender }}
<label>CPF:</label>
{{ form.cpf }}
<label>OAB:</label>
{{ form.oab }}
<label>Telefone:</label>
{{ form.phone }}
<label>E-mail:</label>
{{ form.email }}
{% endfor %}
</form>
&#13;
答案 0 :(得分:1)
请尝试仅保存表单更改。
UserFormSet = formset_factory(UserForm)
if request.method == 'POST':
formset = UserFormSet(request.POST)
if formset.is_valid():
for form in formset:
if form.is_valid():
if form.has_changed():
form.save()