因此,在此表单中,第一个字段保存&更新就好......但是当我想添加一个新对象时,它并没有那么好用。
#Views.py
def edit_auto(request):
car = Auto.objects.filter(user=request.user)
CarFormSet = modelformset_factory(Auto, form=AutoForm, max_num=3)
if request.method == 'POST':
formset = CarFormSet(request.POST, request.FILES, queryset=car)
if formset.is_valid():
formset.save(commit=False)
formset.user = request.user
formset.save()
return render_to_response('manage_users.html', {'message':'Success! The user has been updated!'}, context_instance=RequestContext(request))
else:
formset = CarFormSet(queryset=car)
return render_to_response('mycar.html', locals(), context_instance=RequestContext(request))
#forms.py
class AutoForm(forms.ModelForm):
class Meta:
model = Auto
user = Auto.user
exclude = ('user',)
模板中有什么东西吗?如果它是表单的单个实例,form.user = request.user
通常会保存,但事实并非如此。有什么建议?谢谢你的帮助。
答案 0 :(得分:1)
对于用户分配步骤,只需遍历formset。
...
if request.method == 'POST':
formset = CarFormSet(request.POST, request.FILES, queryset=car)
if formset.is_valid():
formset.save(commit=False)
for form in formset:
form.user = request.user
formset.save()
...