Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django 依赖于其他模型的表单字段需要重新启动服务器_Django_Django Forms - Fatal编程技术网

Django 依赖于其他模型的表单字段需要重新启动服务器

Django 依赖于其他模型的表单字段需要重新启动服务器,django,django-forms,Django,Django Forms,我有以下表格: class AlertForm(forms.Form): user_choices = sorted([(c.id, c.first_name + ' ' + c.last_name) \ for c in User.objects.all()], key=lambda user: user[1]) message = forms.CharField(widget=forms.Textarea()) recipients = forms.M

我有以下表格:

class AlertForm(forms.Form):
    user_choices = sorted([(c.id, c.first_name + ' ' + c.last_name) \
        for c in User.objects.all()], key=lambda user: user[1])
    message = forms.CharField(widget=forms.Textarea())
    recipients = forms.MultipleChoiceField(choices=user_choices,
        widget=forms.SelectMultiple(attrs={'size':'20'}),
        help_text="You will automatically be included with the recipients.")

问题是,如果我使用管理界面或任何其他方法将用户添加到数据库中,我必须在新添加的用户出现在multipleechoice字段之前重新启动服务器。如何避免服务器重新启动?

如果要动态计算
选择
,则需要在表单的
\uuuuuu init\uuuuu
方法中进行计算,而不是在表单定义中。请记住,在加载类定义时,类的主体只执行一次——这就是服务器重启修复问题的原因

您将需要以下内容:

def __init__(self, *args, **kwargs):
    super(AlertForm, self).__init__(*args, **kwargs)
    user_choices = sorted([(c.id, c.first_name + ' ' + c.last_name) \
        for c in User.objects.all()], key=lambda user: user[1])
    self.fields['recipients'].choices = user_choices

您也可以使用聚合、
order\u by
values
将其压缩为查询集,以实现相同的效果。

如果您想动态计算
选择
,则需要在表单的
\u init\u
方法中而不是在表单定义中进行计算。请记住,在加载类定义时,类的主体只执行一次——这就是服务器重启修复问题的原因

您将需要以下内容:

def __init__(self, *args, **kwargs):
    super(AlertForm, self).__init__(*args, **kwargs)
    user_choices = sorted([(c.id, c.first_name + ' ' + c.last_name) \
        for c in User.objects.all()], key=lambda user: user[1])
    self.fields['recipients'].choices = user_choices

您也可以使用聚合、
order\u by
value
将其压缩为查询集,以实现相同的效果。

在搜索过程中,我发现了一个简单得多的解决方案:。它是这样实现的:

class AlertForm(forms.Form):
    message = forms.CharField(widget=forms.Textarea())
    recipients = forms.ModelMultipleChoiceField(queryset=User.objects.all())

此表单字段处理所有详细信息,包括动态更新收件人字段。

在搜索过程中,我发现了一个简单得多的解决方案:。它是这样实现的:

class AlertForm(forms.Form):
    message = forms.CharField(widget=forms.Textarea())
    recipients = forms.ModelMultipleChoiceField(queryset=User.objects.all())

此表单字段处理所有详细信息,包括动态更新收件人字段。

请注意,这并不完全符合您的问题要求:选择文本将是
用户
类上的
\uuuuuunicode\uuuuu
字符串
方法的值(默认情况下仅为
用户名
,而不是“”正如在您的问题中一样。排序顺序也将返回到模型的默认值,而不是您使用的排序顺序。请注意,这与您的问题所要求的并不完全相同:选择文本将是
用户
类上的
\uuuuunicode\uuuuuuu>或
字符串
方法的值(默认情况下,只有
用户名
,而不是您问题中的“”。排序顺序也将返回到模型的默认值,而不是您使用的。