Skip to main content
 首页 » 编程设计

python之Django self.cleaned_data 不工作

2025年05月04日27EasonJim

我是技术新手,所以如果问题太简单,我提前道歉。

我正在使用 self.cleaned_data 获取用户输入的选定数据。它在调用 clean 时起作用,但在我的保存方法上不起作用。

这是代码

表格.py

def clean_account_type(self): 
    if self.cleaned_data["account_type"] == "select": # **here it works** 
        raise forms.ValidationError("Select account type.") 
 
def save(self): 
    acc_type = self.cleaned_data["account_type"] # **here it doesn't, (NONE)** 
 
    if acc_type == "test1": 
        doSomeStuff() 

知道为什么当我调用保存时它不起作用吗?

这是我的views.py

def SignUp(request): 
    if request.method == 'POST': 
        form = SignUpForm(request.POST) 
 
        if form.is_valid(): 
            form.save() 
            return HttpResponseRedirect('/') 

提前致谢。

请您参考如下方法:

clean_<field_name表单上的方法必须返回干净值或引发 ValidationError .来自文档 https://docs.djangoproject.com/en/1.4/ref/forms/validation/

Just like the general field clean() method, above, this method should return the cleaned data, regardless of whether it changed anything or not.

简单的改变是

def clean_account_type(self): 
    account_type = self.cleaned_data["account_type"] 
    if account_type == "select": 
        raise forms.ValidationError("Select account type.") 
    return account_type