在视图中将实例/默认值传递给ModelFormSet以供空表单使用

时间:2010-08-10 21:04:52

标签: python django django-forms

如何预填充ModelFormSet中的排除字段。下面的AuthorFormSet不会在此处采用实例参数,仅采用queryset。那么我如何强制进入的空表单没有NULL / None 用户属性。我希望能够将该用户字段设置为request.user

models.py

class Author(models.Model):
    user = models.ForeignKey(User, related_name='author')
    # assume some other fields here, but not relevant to the discussion.

forms.py

 class AuthorForm(forms.ModelForm):
     class Meta:
         model = Author

 class BaseAuthorFormSet(BaseModelFormSet):
     """will do some clean() here"""
     pass

 AuthorFormSet = modelformset_factory(Author,\
                                    form=AuthorForm, \
                                    formset=BaseAuthorFormSet, extra=1,\
                                    exclude=('user',)
                                    )

views.py

def my_view(request):
    if request.method == 'POST':
        formset = AuthorFormSet(request.POST)
        if form.is_valid(): 
            form.save() # This will cause problems
                        # for the empty form i added,
                       # since user can't  be null.

修改

这就是我在我看来最终做的事情。 Wogan的答案部分正确,我认为它只是错过了所有表格部分的迭代。

for form in formset.forms: 
    form.instance.user = request.user
formset.save()

1 个答案:

答案 0 :(得分:1)

您可以排除模型表单中的字段,然后将这些字段从modelformset_factory创建的表单集中排除。

class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author
        exclude = ('user',)

在您的视图中,将commit=False传递给表单的save()方法,然后手动设置用户字段:

def my_view(request):
    if request.method == 'POST':
        formset = AuthorFormSet(request.POST)
        if formset.is_valid(): 
            for author in formset.save(commit=False):
                author.user = request.user
                author.save()
            formset.save_m2m() # if your model has many to many relationships you need to call this