gpt4 book ai didi

Django 在运行时形成 integerField 设置 max_value

转载 作者:行者123 更新时间:2023-12-05 00:40:49 26 4
gpt4 key购买 nike

我有一个这样的表格:

class SomeForm(forms.Form):
first = forms.IntegerField(max_value= DontWantToSetYet)
second = forms.IntegerField(max_value= DontWantToSetYet)
third = forms.IntegerField(max_value= DontWantToSetYet)

如何在运行时设置 max_values? IE
if request.method == 'POST':
form = SomeForm(request.POST, max_values = {'first':10,'second':50,'third':666})
[...]

最佳答案

您可以设置 __init__ 中字段的最大值方法,如下所示

class SomeForm(forms.Form):
def __init__(self, max_values, *args, **kwargs):
super(SomeForm, self).__init__(*args, **kwargs)
self.fields['first'] = forms.IntegerField(max_value=max_values['first'])
...

first = forms.IntegerField(max_value= DontWantToSetYet)
second = forms.IntegerField(max_value= DontWantToSetYet)
third = forms.IntegerField(max_value= DontWantToSetYet)

编辑:
self.fields['first'].max_value = max_values['first']

我尝试时没有用,像这样重新定义字段定义有效
self.fields['first'] = forms.IntegerField(max_value=max_values['first'])

关于Django 在运行时形成 integerField 设置 max_value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3470741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com