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

olmpazwi  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(116)

我有一个名为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,当我使用initial时,它显示expected length 2 got 1 (got 3)

注意-Love模型与user的关联方式与Demo使用ForeignKey与user的关联方式相同。意味着Love模型是Demo模型的副本。因此查询返回嵌套对象

nfzehxib

nfzehxib1#

您可以使用CheckboxSelectMultipleCheckboxSelectMultiple小部件来填充带有多选复选框的charfield数据,并根据需要覆盖initmwthod中的选择字段。

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

字符串
你可以简单地使用表格在您的views.py,对于FBV

def demo_form_view(request):
   if request.method == 'POST':
       form = DemoForm(request.POST, user=request.user)
       if form.is_valid():
           # Do something with the valid form data
           # For example, save the form
   else:
       form = DemoForm(user=request.user)

   return render(request, 'demo_form.html', {'form': form})

相关问题