简体   繁体   English

具有动态字段值的 Django 表单

[英]Django Forms with dynamic field values

First time using Django Forms.第一次使用 Django 表单。 I'm stuck trying to get the dropdown choices to reload.我一直试图让下拉选项重新加载。 My forms.py is below.我的 forms.py 在下面。 When the database state changes, the choices do not.当数据库状态改变时,选择不会改变。 I suppose that this is because they are defined at a class level, which means the query happens at initialisation of the module?我想这是因为它们是在类级别定义的,这意味着查询发生在模块初始化时? I've found that the only way to get my dropdowns to update is to restart the webserver.我发现让我的下拉菜单更新的唯一方法是重新启动网络服务器。

How can I have the database queries evaluate on every request?如何让数据库查询对每个请求进行评估?

forms.py表格.py

from django import forms 
from app.models import Collection, ErrorMessage, Service

class FailureForm(forms.Form):
    collections = [(collection.value,)*2 for collection in Collection.objects.all()]
    error_messages = [(message.value,)*2 for message in ErrorMessage.objects.all()]
    services = [(service.value,)*2 for service in Service.objects.all()]

    collection = forms.CharField(label='collection', max_length=100, widget=forms.Select(choices=collections))
    error_message = forms.CharField(label='error_message', max_length=400, widget=forms.Select(choices=error_messages))
    service = forms.CharField(label='service', max_length=100, widget=forms.Select(choices=services))
class FailureForm(forms.Form):
    collection = forms.ChoiceField(widget=forms.Select, choices=[])
    ... # etc

    def __init__(self, *args, **kwargs):
        super(FailureForm, self).__init__(*args, **kwargs)
        self.fields['collection'].choices = [(collection.value,)*2 for collection in Collection.objects.all()]
        ... # etc

Note: label='collection' is obsolete.注意: label='collection'已过时。 It will be "collection" by default.默认情况下它将是“集合”。 Same with error_message and service与 error_message 和 service 相同

Did some more digging in the documentation and noticed that callables on a ChoiceField are called every initialisation.在文档中进行了更多挖掘,并注意到 ChoiceField 上的可调用对象在每次初始化时都会被调用。 Therefore, the solution below was I think preferable for me.因此,我认为下面的解决方案对我来说更可取。

class FailureForm(forms.Form):
    collection = forms.ChoiceField(choices=lambda: [(collection.value,)*2 for collection in Collection.objects.all()])
    error_message = forms.ChoiceField(choices=lambda: [(message.value,)*2 for message in ErrorMessage.objects.all()])
    service = forms.ChoiceField(choices=lambda: [(service.value,)*2 for service in Service.objects.all()])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM