自定义MulipleChoiceField

时间:2019-03-19 06:51:48

标签: django forms

我想编写一个自定义窗体,该窗体将从数据框中检索列名,并将这些列用作MultipleChoiceField中的选择。数据框来自模型中的存储文件。

代码产生错误:

project = Project.objects.filter(id=kwargs('pk')).first()
TypeError: 'dict' object is not callable

这是我的代码:

class PredictionCreateModelForm(forms.Form):

global COLUMNS
name = forms.CharField()
model_type = forms.ChoiceField(choices=PREDICTION_TYPE, widget=forms.RadioSelect)
columns = forms.MultipleChoiceField(
    choices=COLUMNS, 
    widget=forms.CheckboxSelectMultiple)

def __init__(self, *args, **kwargs):
    super(PredictionCreateModelForm, self).__init__(*args, **kwargs)
    project = Project.objects.filter(id=kwargs('pk')).first()

    df = pd.read_csv(project.base_file)

    global COLUMNS 
    COLUMNS = df.columns 

class Meta:
    model = PredictionModel
    fields = ['name', 'model_type', 'columns']

1 个答案:

答案 0 :(得分:0)

代码中的 project 变量可告诉是否存在与该“ pk”相关联的任何对象。因此它不是列表或字典。也许您想尝试...

qs = Project.objects.filter(id=kwargs('pk')).exists() # True or False.
if qs:
    project = Project.objects.get(id=kwargs('pk')) # returns the object
else:
    # show error not found message