如何预填充ModelFormSet中的排除字段。下面的AuthorFormSet不会在此处采用实例参数,仅采用queryset。那么我如何强制进入的空表单没有NULL / None 用户属性。我希望能够将该用户字段设置为request.user
class Author(models.Model):
user = models.ForeignKey(User, related_name='author')
# assume some other fields here, but not relevant to the discussion.
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',)
)
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()
答案 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