Django form.save()没有更新form.cleaned_data

时间:2016-12-10 00:23:49

标签: django django-forms django-views

我迷失在这里,无法弄清楚我错过了什么,这可能是愚蠢的事,但我需要另一套眼睛,因为据我所知,这应该是有效的

我尝试做的是允许我的用户以他们习惯的方式输入电话号码,然后接受该输入并从Twilio获取经过验证的国际电话号码并保存。根据定义,这意味着它将采用以下格式 - 这是我需要在数据库中使用它的格式,以便它与应用程序的另一部分很好地交互:

+17085551212

我调试到了那里,我知道值正确进入,如果我得到一个无效的数字等,一切正常。由于某种原因,更新后的值不会传回给表单我在form.save()之前设置了form.cleaned_data [' office_phone']。所以我在数据库中得到原始数字(708)555-1212。​​

forms.py

class ProfileForm(forms.ModelForm):
    office_phone = forms.CharField(max_length=20, label="Office Phone")

views.py

if form.is_valid():
    print (form.cleaned_data['office_phone'])
    pn = form.cleaned_data['office_phone'].replace(" ","")
    try:
        response = validator.phone_numbers.get(str(pn))
        form.cleaned_data['office_phone'] = str(response.phone_number)
        print form.cleaned_data
        form.save()
        success_message = "Your changes have been saved"
    except:
        error_message = "The contact phone number you entered is invalid."

console.output

(708) 555-1212
+17085551212
+17085551212
{'office_phone': '+17085551212'}
<tr><th><label for="id_office_phone">Office Phone:</label></th>
<td><input id="id_office_phone" maxlength="20" name="office_phone" type="text" value="(708) 555-1212" /></td></tr>

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

进行编辑:我意识到我们不应该覆盖save,而应使用自定义验证来清理/验证电话号码:

class ProfileForm(forms.ModelForm):
    office_phone = forms.CharField(max_length=20, label="Office Phone")  

    def clean_office_phone(self):
        value = self.cleaned_data.get("office_phone")
        try:
            value = value.replace(" ", "")
            response = validator.phone_numbers.get(str(value))

        except:
            raise ValidationError("The contact phone number you entered is invalid")

        return str(response.phone_number)

views.py

if form.is_valid():
        form.save()
        success_message = "Your changes have been saved"