2

我有一个简单的表格,

class Compose(forms.Form):
    CHOICES = ()    
    recepient = forms.ChoiceField(choices=CHOICES)
    subject = forms.CharField(max_length=100)
    message = forms.CharField(widget=forms.Textarea)

选择生成为

def mychoiceview(request):
        subscribed_lists, other_lists = getListOfLists(request.user.email)
        for lst in subscribed_lists:
            # list name and list address
            CHOICES = CHOICES + ((lst[1],lst[0]),)

        #Bind data to form and render

基本上,用户订阅了某些列表(来自列表的超集),并且可以(通过下拉菜单)选择他/她想要向哪个列表发送消息。

问题是我找不到如何将“CHOICES”绑定到 django 表单。

一些在线解决方案包括使用模型......但我没有查询集......只是我希望选择字段呈现的动态生成的 id 元组。

有任何想法吗 ?

谢谢 !

4

2 回答 2

1

@nnmware 的解决方案是正确的,但有点太复杂/令人困惑。下面是一个同样有效的更简洁的版本:

class DynamicBindingForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(DynamicBindingForm, self).__init__(*args, **kwargs)
        self.fields['recipient'] = forms.ChoiceField(choices=db_lookup_choices())

wheredb_lookup_choices是对某个数据库或其他动态数据集的调用,并返回一个对列表以供选择:[('val', 'Label'),('val2', 'Label2')]

于 2013-08-02T10:37:12.147 回答
0

如果您使用基于类的视图,则:

鉴于使 mixin 以形式发送请求

class RequestToFormMixin(object):
    def get_form_kwargs(self):
        kwargs = super(RequestToFormMixin, self).get_form_kwargs()
        kwargs.update({'request': self.request})
        return kwargs

class YouView(RequestToFormMixin, CreateView):
    model = YouModel
    # etc

在表单中制作 mixin 以接收来自视图的请求

class RequestMixinForm(forms.Form):
    def __init__(self, *args, **kwargs):
        request = kwargs.pop('request')
        super(RequestMixinForm, self).__init__(*args, **kwargs)
        self._request = request

class Compose(RequestMixinForm):
    subject = forms.CharField(max_length=100)
    message = forms.CharField(widget=forms.Textarea)

    def __init__(self, *args, **kwargs):
        super(Compose, self).__init__(*args, **kwargs)
        subscribed_lists, other_lists = getListOfLists(self._request.user.email)
        for lst in subscribed_lists:
            # list name and list address
            CHOICES = CHOICES + ((lst[1],lst[0]),)    
        self.fields['recipient'] = forms.ChoiceField(choices=CHOICES)
于 2013-07-20T11:06:30.963 回答