python - 如何使用 Django 表单创建过滤下拉列表?

标签 python django

我有这个模型:

class QuestionInstance(models.Model):
    questionsSet = models.ForeignKey(QuestionsSet)
    question     = models.ForeignKey(Question)
    parent       =  models.ForeignKey('self',null=True,blank=True)
    optional     = models.BooleanField(default=False)

我想创建一个下拉列表,用户可以选择一个 QuestionInstance。 必须使用 questionsSet 对其进行过滤。

我已经使用这样的模型进行了测试,但它不起作用:

(基于此How do I filter values in a Django form using ModelForm?)

class FormQuestionSelect(ModelForm):
    instanceList = forms.ChoiceField(choices=[(questionInstance.id, questionInstance.question) for questionInstance in QuestionInstance.objects.all()])

    class Meta:
        model = QuestionInstance
        fields = ('instanceList', )
        widgets = {
            'instanceList': Select(attrs={'class': 'select'}),
        }

    def __init__(self, questionsSet=None, **kwargs):
        super(FormQuestionSelect, self).__init__(**kwargs)
        if questionsSet:
            #Tested many code here to filter, None of them worked :(
            #Is that possible to create instanceList there ?                        

对于这种目的,我不确定使用模型形式是否是个好主意。

在创建或更新模型实例时,模型形式非常有用。 当使用特定的表单时,就像在这种情况下,我在模板中使用自定义表单:

查看

questionInstanceList = QuestionInstance.objects.filter(questionsSet=questionsSet)

模板

<select name="questionInstanceSelect">
    {% for instance in questionInstanceList %}
        <option value="{{ instance.id }}">{{ instance.question.text }}</option>
    {% endfor %}
</select>

并以这种方式处理它们:

instanceList = request.POST.get('questionInstanceSelect')

我很确定有一个正确的方法。

最佳答案

您可以在表单实例化后在表单 __init__ 或 View 中更改 ModelChoiceField 的查询集。但这不能解决客户端的问题。当有人更改 QuestionSet Question 选择框将保持不变

要更新查询集只需更新表单字段的一个

form.fields['parent'].queryset = (QuestionInstance.objects
                                           .filter(questionsSet=questionsSet))

或者如果您更改表单 __init__

self.fields['parent'].queryset = (QuestionInstance.objects
                                           .filter(questionsSet=questionsSet))

但是应该记住,如果 questionsSet 在客户端发生更改,父列表将保持不变。

你会考虑添加客户端代码来更新 parent 的选择列表吗

让我解释一下。

你有模型

class QuestionInstance(models.Model):
    questionsSet = models.ForeignKey(QuestionsSet)
    question     = models.ForeignKey(Question)
    parent       =  models.ForeignKey('self',null=True,blank=True)
    optional     = models.BooleanField(default=False)

此处的父字段链接到self(同一模型)。

让我们使用`这个模型的模型形式

class FormQuestionSelect(ModelForm):
    class Meta:
        model = QuestionInstance

ModelForm 将为每个模型字段创建具有相同名称的字段 然后在它创建之后我们更新 ModelChoiceField(为 ForeignKey 创建)queryset

关于python - 如何使用 Django 表单创建过滤下拉列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19586359/

相关文章:

python - Django 模型中的单元测试外键约束

django - 如何在 Django 中创建和强制执行通用的 OneToOne 关系?

Django 测试 View 模板上下文

python - 从切片对象解析切片信息?

python - 如何配置 vscode 以发现 python 单元测试

python - 在python中处理目录中的特定文件

django - 将额外的上下文传递给 Django Haystack 模板

django - 在 heroku 上部署 django 应用程序出现错误 : DisallowedHost at/Invalid HTTP_HOST header: 'ecommerceyy.herokuapp.com'

Python 正则表达式搜索总是错误的?

python - 无论我输入什么图像,我的 CNN 模型都只能预测第一类