我正在使用ModelForms生成一些用户注册表数据。当我提交表格时,确实添加了记录。但是,现有记录也以表格格式显示。我只是想添加新用户。
注册html表单:
<div class="container">
<h1>Sign up</h1>
<form method="post" action="/users/signup/">{% csrf_token %}
<table>
{{ formset }}
<tr><th><input type="submit" /></th></tr>
</table>
</form>
</div>
声明ModelForms的函数:
def model_signup(request):
ModelFormSet = modelformset_factory(Model)
if request.method == 'POST':
formset = ModelFormSet(request.POST, request.FILES)
if formset.is_valid():
formset.save()
# do something.
else:
formset = ModelFormSet()
return render_to_response("model_signup.html", {
"formset": formset,
}, context_instance=RequestContext(request))
谢谢!
答案 0 :(得分:1)
创建表单集时,您可以specify a queryset。如果您不想显示现有记录,请使用空查询集MyModel.objects.none()
。
ModelFormSet = modelformset_factory(MyModel)
if request.method == 'POST':
formset = ModelFormSet(request.POST, request.FILES, queryset=MyModel.objects.none())
if formset.is_valid():
formset.save()
# do something.
else:
formset = ModelFormSet(queryset=MyModel.objects.none())