0

所以在这个表单集中,第一个字段保存和更新很好......但是当我想添加一个新对象时,它的效果并不好。

#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通常会保存,但不会。有什么建议么?感谢您的帮助。

4

1 回答 1

2

对于用户分配步骤,只需遍历表单集。

...
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()
...
于 2012-09-17T19:49:37.440 回答