python Django:如何为内联模型表单集中的字段设置初始值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1500121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:25:32  来源:igfitidea点击:

Django: How to set initial values for a field in an inline model formset?

pythondjangodefault-valuedjango-forms

提问by Jeff

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.

我有我认为应该是一个简单的问题。我有一个内联模型表单集,我想让一个选择字段具有当前登录用户的默认选择值。在视图中,我使用的是 Django 的身份验证中间件,因此获取用户是访问request.user.

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?

但是,我无法弄清楚的是如何将该用户设置为包含用户列表的选择框 (ModelChoiceField) 中的默认选定值。谁能帮我这个?

回答by Rune Kaagaard

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

回答by mherren

I'm not sure how to handle this in inline formsets, but the following approach will work for normal Forms and ModelForms:

我不确定如何在内联表单集中处理这个问题,但以下方法适用于普通表单和模型表单:

You can't set this as part of the model definition, but you can set it during the form initialization:

您不能将其设置为模型定义的一部分,但您可以在表单初始化期间设置它:

def __init__(self, logged_in_user, *args, **kwargs):
    super(self.__class__, self).__init__(*args, **kwargs)
    self.fields['my_user_field'].initial = logged_in_user

...

form = MyForm(request.user)

回答by Chris McGinlay

I'm using Rune Kaagaard's idea above, except I noticed that formsets provide an extra_forms property: django.forms.formsets code

我正在使用上面的 Rune Kaagaard 的想法,但我注意到表单集提供了一个 extra_forms 属性:django.forms.formsets 代码

@property
def extra_forms(self):
    """Return a list of all the extra forms in this formset."""
    return self.forms[self.initial_form_count():]

So, sticking with the example above:

所以,坚持上面的例子:

formset = MyFormset(instance=myinstance)
user = request.user
for form in formset.extra_forms:
    form.initial['user'] = user.pk

Saves having to test any initial forms, just provide default for extra forms.

无需测试任何初始表单,只需为额外表单提供默认值。