gpt4 book ai didi

python - 将实例/默认值传递给 ModelFormSet,以便在 View 中使用空表单

转载 作者:太空宇宙 更新时间:2023-11-04 06:30:36 27 4
gpt4 key购买 nike

如何在 ModelFormSet 中预填充 exclude 字段。下面的 AuthorFormSet 在这里没有使用 instance 参数,只有 queryset。那么我如何强制进入的空表单不具有 NULL/None user 属性。我希望能够将该用户字段设置为 request.user

模型.py

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

表单.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',)
)

View .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()

最佳答案

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

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

在您的 View 中,将 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

关于python - 将实例/默认值传递给 ModelFormSet,以便在 View 中使用空表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3453416/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com