Django ModelForm小部件覆盖问题

时间:2016-12-21 18:34:25

标签: django django-forms

过去几天我一直在尝试使用模型表单来使用与模型中不同的小部件。我正在尝试制作一个动态更新Slack中的通道选项列表的表单,我在使表单工作时遇到问题。

型号:

set firstLine to item 1 of paragraphs of input
if firstLine starts with "/*" and firstLine ends with "*/" then
    return text 4 thru -4 of firstLine
else
    return "unknown"
end if

表单尝试1:

class Team(models.Model):
    team_id = models.CharField(editable=False, primary_key=True, max_length=30)
    access_token = models.CharField(max_length=128, editable=False)
    post_channel = models.CharField(max_length=21, default=None)
    approval_channel = models.CharField(max_length=21, default=None)
    last_edit = models.CharField(max_length=21, default=None)
    admin_only_approval = models.BooleanField(default=True)
    admin_only_edit = models.BooleanField(default=True)

每次提交表单时,都会说数据无效,并且选项字段的输入不是可用选项之一。

表单尝试2:

class TeamSettingsForm(forms.ModelForm):
    post_channel = forms.ChoiceField()
    approval_channel = forms.ChoiceField()

    def __init__(self, *args, **kwargs):
        super(TeamSettingsForm, self).__init__(*args, **kwargs)

        slack = Slacker(kwargs['instance'].access_token)

        priv_ch = [(g['id'], g['name']) for g in slack.groups.list().body['groups'] if not g['is_archived']]
        pub_ch = [(c['id'], c['name']) for c in slack.channels.list().body['channels'] if not c['is_archived']]
        users = [(u['id'], u['profile']['real_name']) for u in slack.users.list().body['members'] if not u['deleted']]

        self.fields['post_channel'].widget.choices=tuple(pub_ch)
        self.fields['approval_channel'].widget.choices=tuple(pub_ch + priv_ch + users)

    class Meta:
        model = Team
        fields = ['post_channel', 'approval_channel', 'admin_only_approval',
                  'admin_only_edit']

表单尝试3:

class TeamSettingsForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(TeamSettingsForm, self).__init__(*args, **kwargs)

        slack = Slacker(kwargs['instance'].access_token)

        priv_ch = [(g['id'], g['name']) for g in slack.groups.list().body['groups'] if not g['is_archived']]
        pub_ch = [(c['id'], c['name']) for c in slack.channels.list().body['channels'] if not c['is_archived']]
        users = [(u['id'], u['profile']['real_name']) for u in slack.users.list().body['members'] if not u['deleted']]

        self.fields['post_channel'].widget = forms.ChoiceField(choices=tuple(pub_ch))
        self.fields['approval_channel'].widget = forms.ChoiceField(choices=tuple(pub_ch + priv_ch + users))

    class Meta:
        model = Team
        fields = ['post_channel', 'approval_channel', 'admin_only_approval',
                  'admin_only_edit']

尝试2和3甚至不允许页面呈现。

我一直在尝试不同的选项in the Django documentation,但它并没有那么有用。

1 个答案:

答案 0 :(得分:0)

这最终为我工作

self.fields['post_channel'].widget = forms.Select(choices=tuple(pub_ch))