使用数据库中存在的数据呈现 CheckBoxSelectMultiple 表单。 [初始值是来自数据库的查询集]

问题描述 投票:0回答:1

我有一个名为

DemoForm
的表格,与模型相关
Demo

class Demo(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    ans = models.CharField(max_length=1024)

其形式为

class DemoForm(forms.ModelForm):
    class Meta:
        model = Demo
        exclude = ('user',)
        widgets = {'ans': forms.CheckboxSelectMultiple}

我想使用

queryset
渲染此表单,我尝试了不同的方法,例如

form = DemoForm(initial=Love.objects.filter(user=request.user))


<form=GoodForm()  
form.fields["ans"].queryset = Love.objects.filter(user=request.user) >


form=DemoForm(instance=Love.objects.filter(user=request.user)


form=DemoForm(instance=request.user.love_set.all())

有时它会显示

no _Meta present
,当我使用首字母时,它会显示
expected  length 2 got 1 (got 3)

注意 -

Love
模型与用户相关,就像
Demo
与使用
ForeignKey
的用户相关一样。表示
Love
模型是
Demo
模型的副本。所以查询返回嵌套对象

django django-models django-forms django-views
1个回答
0
投票

您可以使用

MultipleChoiceField
CheckboxSelectMultiple
小部件使用多选复选框填充 charfield 数据,并根据要求覆盖 init mwthod 中的选择字段。

class DemoForm(ModelForm):
   ans = MultipleChoiceField(widget=CheckboxSelectMultiple)

class Meta:
    model = Demo
    exclude = ('user',)

def __init__(self, *args, user=None, **kwargs):
    super(DemoForm, self).__init__(*args, **kwargs)

    if user:
        # Assuming Love model has a CharField named 'ans'
        love_objects = Love.objects.filter(user=user)
        choices = [(obj.ans, obj.ans) for obj in love_objects]
        self.fields['ans'].choices = choices
© www.soinside.com 2019 - 2024. All rights reserved.