这是一个表格,
MyForm
,它有一个字段my_field
,初始值为 10.
forms.py
from django import forms
class MyForm(forms.Form):
my_field = forms.IntegerField(
initial=10,
widget=forms.NumberInput(
{
'class': f'form-control',
}
),
label='',
)
无论何时从这个表单生成一个表单集,它都会忽略初始值,否则它工作得很好:
views.py
from django.forms import formset_factory
from django.shortcuts import render
from myapp.forms import MyForm
def index(request):
factory = formset_factory(MyForm)
match request.method:
case 'POST':
formset = factory(request.POST)
if formset.is_valid():
print(formset.cleaned_data)
case _:
formset = factory()
return render(request, 'index.html', {'formset': formset})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{{ form }}
{% endfor %}
<button type="submit">Submit</button>
</form>
</body>
</html>
下面是当我只提交表单而不修改字段值时会发生什么。我希望在清理后的表格中看到 10 的值,但我什么也没得到。
[{}]
[29/Mar/2023 01:07:34] "POST / HTTP/1.1" 200 867
尽管存在
request.POST
中的值
<QueryDict: {'csrfmiddlewaretoken': ['nH5YM6syXup35jiI0O0XKgq3DsWVr4UuMb6ZvRm62gl5F3vtCYZAIiK9v0WWChZN'], 'form-TOTAL_FORMS': ['1'], 'form-INITIAL_FORMS': ['0'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-my_field': ['10']}>
然后我将值设置为 5,它工作正常:
[{'my_field': 5}]
[29/Mar/2023 01:07:47] "POST / HTTP/1.1" 200 866
我相信你需要在处理表格时需要使用首字母:
def index(request):
factory = formset_factory(MyForm, initial=[{'my_field': 10}]) # CHANGED
match request.method:
case 'POST':
formset = factory(request.POST, initial=[{'my_field': 10}]) # CHANGED
if formset.is_valid():
print(formset.cleaned_data)
case _:
formset = factory()
return render(request, 'index.html', {'formset': formset})
查看文档在末尾使用带有表单集的初始数据:
如果你使用一个首字母来显示一个表单集,你应该通过 在处理该表单集的提交时使用相同的首字母,以便 formset 可以检测用户更改了哪些表单。例如, 你可能有这样的东西: ArticleFormSet(request.POST, 初始=[...]).