更新时间:2023-01-10 15:34:41
诀窍是使用"ModelFormset"而不是仅使用表单集,因为它们允许使用查询集进行初始化.这些文档是此处,您可以做什么在创建模型表单集时提供一个form = *,在实例化表单集时提供queryset = *.form = *争论没有得到充分的记录(必须在代码中进行一些挖掘以确保它确实存在).
The trick is to use a "ModelFormset" instead of just a formset since they allow initialization with a queryset. The docs are here, what you do is provide a form=* when creating the model formset and queryset=* when your instantiating the formset. The form=* arguement is not well documented (had to dig around in the code a little to make sure it is actually there).
def edit(request):
PointFormSet = modelformset_factory(Point, form = PointForm)
qset = Point.objects.all() #or however your getting your Points to modify
formset = PointFormset(queryset = qset)
if request.method == 'POST':
#deal with posting the data
formset = PointFormset(request.POST)
if formset.is_valid():
#if it is not valid then the "errors" will fall through and be returned
formset.save()
return #to your redirect
context_dict = {'formset':formset,
#other context info
}
return render_to_response('your_template.html', context_dict)
因此,代码很容易遍历.如果请求是GET,则将实例化的表单返回给用户.如果请求是POST,并且表单是 not .is_valid()
,则错误掉线"并在同一模板中返回.如果请求是POST且数据有效,那么将保存表单集.
So the code walks through easily. If the request is a GET then the instantiated form is returned to the user. If the request is a POST and the form is not .is_valid()
then the errors "fall through" and are returned in the same template. If the request is a POST and the data is valid then the formset is saved.
希望有帮助.
-将