将数据绑定到django的表单选择域

时间:2013-07-20 09:45:36

标签: django django-forms choicefield

我有一个简单的表格,

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

Chocies生成为

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

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

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

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

有什么想法吗?

谢谢!

2 个答案:

答案 0 :(得分: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())

其中db_lookup_choices是对某些数据库或其他动态数据集的调用,并返回选项对的列表:[('val', 'Label'),('val2', 'Label2')]

答案 1 :(得分:0)

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

在视图中make 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

以表格形式make 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)