我有一个称为django的字段,用于is_private
指示用户完成的发布是否为私人。如果发布是私人的,则private_room
必须提到一个称为的特定字段,否则需要一个名为的字段public_room
。
在clean_private_room
和clean_public_room
字段中,我正在检查的值is_private
。如果房间是私人的,则在该clean_public_room
方法中,我只返回一个空字符串""
,clean_private_room
否则返回相同的字符串,否则我将继续进行验证。
问题是self.cleaned_data.get('is_private')
在这两种方法中,with的检查返回不同的结果。我尝试调试代码,然后将self.cleaned_data
值打印到终端,在其中一种方法中,清除的数据包含一个表单字段,在另一种方法中包含完整的发布值。
这是我的代码的一部分,请阅读其中的注释,以查看我打印的位置和打印的内容。我不知道为什么会这样。
class RoomForm( forms.ModelForm ):
...
def clean_is_private( self ):
if not 'is_private' in self.cleaned_data:
raise forms.ValidationError("please select the type of room (private/public)")
return self.cleaned_data.get("is_private")
def clean_public_room( self ):
print "<clean_public_room>"
# !!!!!!!!!
# when printing this one I only get one form value which is: public_room
print self.cleaned_data
if self.cleaned_data.get("is_private"):
return ""
# otherwise....
if not self.cleaned_data.get("public_room"):
raise forms.ValidationError(
'you need to mention a public room'
)
return self.cleaned_data[ 'public_room' ]
def clean_private_room( self ):
print "<clean_private_room>"
# !!!!!!!!!
# when printing this one I get all form values: public_room, private_room, is_private
print self.cleaned_data
if not self.cleaned_data.get("is_private"):
return ""
# otherwise....
if not self.cleaned_data.get("private_room"):
raise forms.ValidationError(
'you need to mention a private room'
)
return self.cleaned_data[ 'private_room' ]
表单字段将按照它们在表单中定义的顺序进行清理。因此,您只需要在字段列表中的is_private
之前放置字段public_room
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句