Django:如何为内联模型表单集中的字段设置初始值? [英] Django: How to set initial values for a field in an inline model formset?
问题描述
我认为应该是一个简单的问题.我有一个内联模型表单集,我想让一个选择字段具有当前登录用户的默认选择值.在视图中,我使用的是 Django 的 Authentication 中间件,因此获取用户是访问 request.user
的简单问题.
I have what I think should be a simple problem. I have an inline model formset, and I'd like to make a select field have a default selected value of the currently logged in user. In the view, I'm using Django's Authentication middleware, so getting the user is a simple matter of accessing request.user
.
不过,我无法弄清楚的是如何将该用户设置为包含用户列表的选择框 (ModelChoiceField) 中的默认选定值.谁能帮我这个?
What I haven't been able to figure out, though, is how to set that user as the default selected value in a select box (ModelChoiceField) containing a list of users. Can anyone help me with this?
推荐答案
这可以解决问题.它的工作原理是设置所有额外"表单的初始值.
This does the trick. It works by setting the initial values of all "extra" forms.
formset = MyFormset(instance=myinstance)
user = request.user
for form in formset.forms:
if 'user' not in form.initial:
form.initial['user'] = user.pk
这篇关于Django:如何为内联模型表单集中的字段设置初始值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!