Render a CheckBoxSelectMultiple form using the data present in Database. [initial value is a queryset from DB]

回眸只為那壹抹淺笑 提交于 2019-12-17 17:16:08

问题


I have a form called DemoForm which is related to model Demo

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

and the form for this is

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

I want to render this form using a queryset I have tried different approaches like

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())

Sometimes it is showing no _Meta present and when I use initial, it shows the expected length 2 got 1 (got 3)

NOTE- The Love model is related to user in the same way as the Demo is related to user using ForeignKey. Means the Love model is a copy of Demo model. So the query returns nested objects

来源:https://stackoverflow.com/questions/57884248/render-a-checkboxselectmultiple-form-using-the-data-present-in-database-initia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!