简体   繁体   English

Django:如何为内联模型formset中的字段设置初始值?

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

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. 我有一个内联模型formset,我想让一个select字段具有当前登录用户的默认选择值。 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. 但是,我无法弄清楚的是,如何将该用户设置为包含用户列表的选择框(ModelChoiceField)中的默认选定值。 Can anyone help me with this? 谁能帮我这个?

I'm not sure how to handle this in inline formsets, but the following approach will work for normal Forms and ModelForms: 我不确定如何在内联表单集中处理这个问题,但以下方法适用于普通的Forms和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)

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

I'm using Rune Kaagaard's idea above, except I noticed that formsets provide an extra_forms property: django.forms.formsets code 我正在使用上面的Rune Kaagaard的想法,除了我注意到formsets提供了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. 保存必须测试任何初始表单,只提供额外表单的默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM