Django动态表单



我正在制作Django web应用程序,我不知道如何解决这个问题。我将非常感激你的帮助。这里有forms。py

CHOICES =(
("1", "sys_1"),
("2", "sys_2"),
("3", "sys_3"),
("4", "sys_4"),
)
#and so on, lots of elements
Class ExampleForm(forms.Form):
text = forms.CharField()
list = forms.MultipleChoiceField(choices=CHOICES,widget=forms.CheckboxSelectMultiple)

我想实现的是,如果用户在文本字符字段中写入内容,列表应该根据输入的内容动态更改选择的内容。此外,列表必须记住标记复选框。示例(步骤列表):

1. user inputs something in the char field
2. the list is changing
3. user marks some checkboxes
4. user deletes content in the char field 
5. the list is changing and displaying all elements but remember marked 
checkboxes

你可以使用forms.MultipleChoiceField()获取数据库的对象,然后用一个特殊的键在index.html中服务它们,然后通过javascript过滤选项,像这样:

首先为author创建模型。

models.py

from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name

通过查询数据库来指定选择表单和选项。

forms.py

from django import forms
from . import models
CHOICES =[]
def choice():
key = 0
query = models.Author.objects.all()
for obj in query:
CHOICES.append((key, obj))
key += 1
return CHOICES
class ExampleForm(forms.Form):
author = forms.MultipleChoiceField(choices=choice(),
initial='',
required=False,
widget=forms.Select(attrs={'id': 'selection'}))

发送你的表单到index.html文件

views.py

from django.shortcuts import render
from . import forms
def home(request):
form = forms.ExampleForm
return render(request, 'base.html', {'form': form})

最后在index.html中使用{{ form }},并在输入框中指定一个oninput事件以按每个新字母搜索。在script标签中定义一个函数,使用includes()方法在select options中逐一搜索。

index . html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<style>
</style>
</head>
<body>
<input type="text" oninput="myFunction(this.value)">
{{form}}


<script>
function myFunction(value) {
var x = document.getElementById("selection");
for (i = 0; i < x.length; i++) {
text = x.options[i].text;
if (text.includes(value) === false) {
x.remove(i);
}
}

}
</script>

</body>
</html>

我还使用remove()方法在selectionObj.remove(indexNumber)结构中删除每个选项。