Django UpdateView扩展了Form字段选项

时间:2017-11-22 14:57:06

标签: python django

我有一个名为ipts字段的Django表单,默认情况下其内容为choices=(('', '-'*20),)

UpdateView中,我使用更多选项扩展此列表。 因此,在get_context_data我得到表单并扩展该列表。

choices = form.fields['ipts'].choices
choices = choices.extend( [('IPTS-123', 'IPTS-454545'),] )

为了确保选项填充得很好,我在render_to_response方法中打印了form.fields['ipts'].choices,我得到了我的期望:

[('', '--------------------'), ('IPTS-123', 'IPTS-454545')]

但是模板没有填充这些选项!只需初始值可供选择:('', '--------------------')

如何在基于类的视图中扩展选择字段?

欢迎提出建议。感谢。

修改

这里是视图代码:

class ProfileReductionUpdate(LoginRequiredMixin, SuccessMessageMixin,
                             UpdateView):
    '''

    '''
    model = UserProfile
    form_class = UserProfileReductionForm
    template_name = 'users/profile_reduction_form.html'
    # fields = '__all__'
    success_url = reverse_lazy('index')
    success_message = "Your Profile for the Reduction was updated successfully."

    def get(self, request, *args, **kwargs):
        print("*** get")

        return super(ProfileReductionUpdate, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        print("*** get_context_data")

        context = super(ProfileReductionUpdate, self).get_context_data(**kwargs)

        from pprint import pprint
        # pprint(context)
        import copy
        form = context['form']
        print("Form:")
        pprint(form)

        choices = form.fields['ipts'].choices
        choices = choices.extend( [('IPTS-123', 'IPTS-454545'),] )

        pprint(form.fields['ipts'].choices)

        # form.fields['ipts'].choices = choices

        context['form'] = form
        pprint(context['form'].fields['ipts'].choices)
        return context

    def render_to_response(self, context, **response_kwargs):

        print("*** render_to_response")
        from pprint import pprint
        pprint(context)
        pprint(response_kwargs)


        form = context['form']
        print("Form:")
        pprint(form)
        print("Form ipts choices:")
        pprint(form.fields['ipts'].choices)
        pprint(form.fields['ipts']._choices)

        # pprint(dir(form.fields['ipts']))

        return super(ProfileReductionUpdate, self).render_to_response(context, **response_kwargs)

这里输出:

*** get
[22/Nov/2017 10:22:14] DEBUG [server.apps.users.models:60] QuerySet
*** get_context_data
Form:
<UserProfileReductionForm bound=False, valid=Unknown, fields=(ipts;experiment)>
[('', '--------------------'), ('IPTS-123', 'IPTS-454545')]
[('', '--------------------'), ('IPTS-123', 'IPTS-454545')]
*** render_to_response
{'form': <UserProfileReductionForm bound=False, valid=Unknown, fields=(ipts;experiment)>,
 'object': <UserProfile: rhf>,
 'userprofile': <UserProfile: rhf>,
 'view': <server.apps.users.views.ProfileReductionUpdate object at 0x7f0d29d14b70>}
{}
Form:
<UserProfileReductionForm bound=False, valid=Unknown, fields=(ipts;experiment)>
Form ipts choices:
[('', '--------------------'), ('IPTS-123', 'IPTS-454545')]
[('', '--------------------'), ('IPTS-123', 'IPTS-454545')]

编辑2:

形式:

class UserProfileReductionForm(forms.ModelForm):
    '''
    '''
    def __init__(self, *args, **kwargs):
        super(UserProfileReductionForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_class = 'form-horizontal'

        self.helper.layout.append(Submit('submit', 'Save'))
        self.helper.layout.append(Button('cancel', 'Cancel',
                                         css_class='btn-default',
                                         onclick="window.history.back()"))
    class Meta:
        model = UserProfile
        # exclude = ['user']
        fields = ['ipts', 'experiment']

型号:

ipts = models.CharField(
        "Integrated Proposal Tracking System (IPTS)",
        max_length=20,
        blank=True,
        choices=(('', '-'*20),)

1 个答案:

答案 0 :(得分:0)

OK!我想通了!

填充的字段是: form.fields['ipts'].widget.choices

而不是: form.fields['ipts'].choices

希望它能帮助别人!