Django在ModelMultipleChoiceField和CheckboxSelectMultiple()小部件中渲染表单初始值

2 投票
1 回答
3182 浏览
提问于 2025-04-17 22:32

我有一个表单:

class TutorForm(SignupForm):
   subjects = forms.ModelMultipleChoiceField(queryset=Subject.objects.all(),
                                          widget=forms.CheckboxSelectMultiple())

我有一个叫做 TutorUpdateForm 的子表单,它是从 TutorForm 继承而来的,并且在初始化方法中设置了初始值。

self.fields['subjects'].initial = current_user.subjects.all()

但是在我的模板中,这些值并没有被选中(在视图中这些值是存在的,所以设置初始值是有效的)。我该如何在模板中强制让输入框被选中呢?

编辑(初始化代码)

def __init__(self, *args, **kwargs):
    current_user = None
    try:
        current_user = kwargs.pop('user')
    except Exception:
        pass
    super(TutorUpdateForm, self).__init__(*args, **kwargs)

    for field in _update_exclude:
        self.fields.pop(field)

    if current_user:
        self.fields['subjects'].initial = current_user.subjects.all()

1 个回答

5

你应该把初始值传递给super的调用,同时你也可以为dict.pop设置一个默认值,这样就不需要用到try/except了。

def __init__(self, *args, **kwargs):
    current_user = kwargs.pop('user', None)

    initial = kwargs.get('initial', {})
    if current_user:
        initial.update({'subjects': current_user.subjects.all()})
    kwargs['initial'] = initial

    super(TutorUpdateForm, self).__init__(*args, **kwargs)

    for field in _update_exclude:
        self.fields.pop(field)

这里有一个链接,里面是关于表单动态初始值的文档。

撰写回答