从对象的字典创建Django表单 [英] Creating a Django form from a dictionary of objects

查看:189
本文介绍了从对象的字典创建Django表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得这样做真的很简单,但经过几天的尝试,我正式无能为力。



我有一个字典,键是对象这些值是对象的列表。以下是我想如何使用该信息来构造一个表单:

 对于字典中的对象:
name_of_field = object。 slug
name_of_field = forms.ModelMultipleChoiceField(widgets = forms.CheckboxSelectMultiple,queryset = dictionary [object])

当然,只要把name_of_field放在那里两次就不能生成动态命名的字段。这实际上是使用它迭代的最终对象创建一个名为name_of_field的单个字段。我希望它会为字典中的每个键创建一个字段,使用关键对象的slug命名并使用该键的值的选择集。



有没有办法循环通过这个字典创建我想要的表单字段?我觉得答案在于超级分类 __ init __ ,但是我仍然不能围绕如何获取多个不同名称的字段。

解决方案

你不会说你正在使用这个代码。您应该将其放入窗体的 __ init __ 方法中,从中可以引用 self.fields

  class DynamicForm(forms.Form):
def __init __(self,* args,** kwargs):
dynamic_fields = kwargs.pop('dynamic_fields')
super(DynamicForm,self).__ init __(* args,** kwargs)
为key,dynamic_fields中的值:
self.fields [key。 slug] = forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple,queryset = value)


I feel like this must be really simple, but after a couple of days of trying I'm officially clueless.

I have a dictionary where the keys are objects and the values are lists of objects. Here's how I want to use that info to construct a form:

for object in dictionary:
    name_of_field = object.slug
    name_of_field = forms.ModelMultipleChoiceField(widgets=forms.CheckboxSelectMultiple, queryset=dictionary[object]) 

Of course, just putting name_of_field in there twice doesn't work to generate dynamically named fields. What this actually does is create a single field called "name_of_field" using the final object it iterates over. I wish it would create a field for every key in the dictionary, named using the key object's slug and with a choice set of that key's values.

Is there a way to loop through this dictionary and create the form fields I want? I feel like the answer lies in superclassing __init__, but I still can't wrap my head around how to get multiple fields with different names.

解决方案

You don't say where you are using this code. You should be putting it into the form's __init__ method, from where you can reference self.fields:

class DynamicForm(forms.Form):
    def __init__(self, *args, **kwargs):
        dynamic_fields = kwargs.pop('dynamic_fields')
        super(DynamicForm, self).__init__(*args, **kwargs)
        for key, value in dynamic_fields:
            self.fields[key.slug] = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=value)

这篇关于从对象的字典创建Django表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆