【问题标题】:Binding data to django's form choicefield将数据绑定到 django 的表单选择字段
【发布时间】:2013-07-20 09:45:35
【问题描述】:

我有一个简单的表格,

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 元组,我希望选择字段呈现。

有什么想法吗?

谢谢!

【问题讨论】:

标签: django django-forms choicefield


【解决方案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')]

【讨论】:

  • 在这个解决方案中你在哪里访问“请求”?
  • 您可以控制构造函数,因此只需将其作为参数传入即可。但请务必不要将其传递给父类。
  • 用户问-如何发送参数?在他的变体 - 参数请求中。你的回答不具体。
  • class DynamicBindingForm(forms.Form): def __init__(self, request, *args, **kwargs): super(DynamicBindingForm, self).__init__(*args, **kwargs) self.fields['recipient'] = forms.ChoiceField(choices=get_choices(request))
  • 您在吹毛求疵,而 CBV 不一定更好,因此请删除您的反对票。来自文档:“基于类的视图提供了一种将视图实现为 Python 对象而不是函数的替代方法。它们不会替换基于函数的视图”
【解决方案2】:

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

在视图中制作 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 2012-08-12
    • 1970-01-01
    相关资源
    最近更新 更多