基于数据库中的值的多个文本框和复选框(Django)

时间:2022-12-02 17:41:35

I have a model that looks something like this

我有一个看起来像这样的模型

ID, name, isValue, Value

ID,name,isValue,Value

What I want the logic to do is like this in layman terms :

我希望逻辑做的就是外行术语:

if isValue is false, present the user with a textbox so that he can fill it in,

如果isValue为false,则向用户显示一个文本框,以便他可以填写,

else , present the user with a checkbox

否则,向用户显示一个复选框

In the database, all of these columns are filled in except Value column. I don't really need any code but I appreciate if anybody can show me how to move on from here.

在数据库中,除Value列之外,所有这些列都被填充。我真的不需要任何代码,但我很感激,如果有人能告诉我如何从这里继续前进。

Just to start off, I'm not sure whether it is possible to pass the (isValue=false) objects to the checkbox widget, and pass the (isValue=True) objects to the textbox widget, and then display it on my template, just not sure how. I did something like this to separate the objects. So what I wanted is to display all 13 entries(for example, there are 13 entries in that table) with its name and checkbox/textbox based on isValue.

刚开始,我不确定是否可以将(isValue = false)对象传递给复选框小部件,并将(isValue = True)对象传递给文本框小部件,然后将其显示在我的模板上,只是不确定如何。我做了类似这样的事情来分离对象。所以我想要的是显示所有13个条目(例如,该表中有13个条目),其名称和基于isValue的复选框/文本框。

checkboxx = []
textboxx  = []

items = Items.objects.all()
for i in items:
       if i.isValue == False:
          checkboxx.append(i)
       else
          textboxx.append(i)

1 个解决方案

#1


1  

Use a custom form. Then in it's __init__ method assign a Textarea or CheckboxInput widget as the field's widget based on whatever evaluation you like.

使用自定义表单。然后在它的__init__方法中根据您喜欢的任何评估将Textarea或CheckboxInput小部件指定为字段的小部件。

class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)

        if self.instance.isValue:
            self.fields['myfield'].widget = forms.Textarea()
        else:
            self.fields['myfield'].widget = forms.CheckboxInput()

Above is a simplified example. You'll have to modify to fit your logic, but the basic principle applies.

以上是一个简化的例子。您必须修改以适合您的逻辑,但基本原则适用。

#1


1  

Use a custom form. Then in it's __init__ method assign a Textarea or CheckboxInput widget as the field's widget based on whatever evaluation you like.

使用自定义表单。然后在它的__init__方法中根据您喜欢的任何评估将Textarea或CheckboxInput小部件指定为字段的小部件。

class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)

        if self.instance.isValue:
            self.fields['myfield'].widget = forms.Textarea()
        else:
            self.fields['myfield'].widget = forms.CheckboxInput()

Above is a simplified example. You'll have to modify to fit your logic, but the basic principle applies.

以上是一个简化的例子。您必须修改以适合您的逻辑,但基本原则适用。