我的表单中有一个非必填字段,称为into_alias
。在我的视图中调用form.valid()时,它正在尝试运行clean_into_alias
来验证此字段。
但是,当没有提供该字段的值时,它仍在尝试清理它,并且出现此错误:
DoesNotExist at /department/b6c1f70de01d488faac5247f54414b5f/merge/delete
{'name_short': ''}
forms.py
class DeptMergeDeleteForm(forms.Form):
def __init__(self, *args, **kwargs):
self.department = kwargs.pop('department', None)
super(DeptMergeDeleteForm, self).__init__(*args, **kwargs)
into_alias = forms.CharField(
required = False,
max_length = 51,
label = mark_safe("""When you delete this department, do you want to merge its members into another department? If so, please provide the alias of the department that you want to merge these employees into "e.g. @tech_support")"""),
validators=[valid_dept_alias_chars, valid_dept_alias_exists,],
)
def clean_into_alias(self):
dept_drop = self.department
data = self.cleaned_data['into_alias']
dept_into = Department.nodes.get(name_short=data) #<------- ERROR -------
if dept_into == dept_drop:
raise ValidationError("You cannot merge your members into the same department that you are about to drop ;)")
# return the cleaned data
return data
也许{'name_short': ''}
是一个空字符串,不是None?我在本地变量中看到data =''
答案 0 :(得分:0)
data = self.cleaned_data.get('into_alias', None)
if data is not None:
try:
dept_into = Department.nodes.get(name_short=data)
if dept_into == dept_drop:
raise ValidationError("You cannot merge your members into the same department that you are about to drop ;)")
except Department.DoesNotExist:
pass
return data