gpt4 book ai didi

python - 如果在 django 表单中设置了另一个字段,则验证字段

转载 作者:太空宇宙 更新时间:2023-11-04 09:08:51 25 4
gpt4 key购买 nike

虽然我阅读了文档,但我对 Django 表单验证感到很迷茫。

我定义了如下形式:

class NewProjAccount(NewAccount):
def __init__(self, perforce='', *args, **kwargs):
super(NewProjAccount, self).__init__(*args, **kwargs)
print perforce
if 'on' in perforce:
self.fields['perforce_depot_size'].widget.attrs[
'required'] = True

site = forms.ChoiceField(choices=SITE_CHOICES, required=False,
label="Site")
project_name = forms.CharField(max_length=25, required=True,)
disk_usage = forms.IntegerField(max_value=PROJ_MAX_SIZE_GB,
)
homes = forms.MultipleChoiceField(choices=SITE_CHOICES, required=False,
widget=
forms.widgets.CheckboxSelectMultiple(),
label="Remote Homes")
perforce_depot = forms.BooleanField(required=False)
perforce_depot_size = forms.IntegerField(max_value=PERFORCE_MAX_SIZE_GB,
required=False)

class ReviewProjAccount(NewProjAccount):
site = forms.CharField(max_length=20, required=False,
label="Site")
project_name = forms.CharField(max_length=25, required=True,)
homes = forms.CharField(label="Remote Homes")
perforce_depot = forms.BooleanField(required=False,
widget=forms.widgets.CheckboxInput(
attrs={'disabled': 'disabled'}))

两种形式都继承自:

class NewAccount(forms.Form):
"""
Base class for all the account type
"""
def __init__(self, readonly=False, *args, **kwargs):
super(NewAccount, self).__init__(*args, **kwargs)

if readonly:
for field in self.fields.itervalues():
field.widget.attrs['readonly'] = 'readonly'

我的想法是像这样使用这种形式:

 if request.method == 'POST':           
try:
form = NewProjAccount(perforce=request.POST['perforce_depot'],
data=request.POST)
except MultiValueDictKeyError:
print "caugh"
if request.POST['perforce_depot_size']:
form = ReviewProjAccount(data=initial_val,
readonly=True)
else:
form = NewProjAccount(data=request.POST)

然而,这会导致一个非常复杂的 View 函数,其中可能包含“if”和“else”以及'尝试...示例'...

所以,我的问题是:

有没有一种简单的方法来定义表单中字段之间的关系,这样当一个是 True,它会触发另一个字段的验证器?
就我而言,我想当用户选择时:perforce_depot = True,或者 'on' perforce_depot_size 应该将属性 required 设置为 True

最佳答案

可以看看Cleaning and validating fields that depend on each other

from django import forms

class NewProjAccount(forms.Form):
#form attributes

def clean(self):
cleaned_data = super(NewProjAccount, self).clean()
perforce_depot = cleaned_data.get("perforce_depot")
perforce_depot_size = cleaned_data.get("perforce_depot_size")

if perforce_depot and not perforce_depot_size:
raise forms.ValidationError("perforce_depot_size needs to be set to true.")

# Always return the full collection of cleaned data.
return cleaned_data

此外,我建议您看一下 django 的 ModelForm ,这将极大地减少您的代码,并使其更加简单

关于python - 如果在 django 表单中设置了另一个字段,则验证字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17476345/

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