Reputation: 252
I'm lost here and can't figure out what I'm missing, which is probably something stupid, but I need another set of eyes because as far as I can tell this should be working.
What I'm trying to do is allow my users to enter phone numbers in ways they are used to seeing, but then take that input and get a validated international phone number from Twilio and save it. By definition that means it will be in the following format - which is the format I need to have it in the database so that it interacts well with another part of the application:
+17085551212
I've debugged to the point there I know the values are coming in correctly, everything works right if I get an invalid number, etc. For some reason, the updated value is not being passed back to the form when I set form.cleaned_data['office_phone'] prior to the form.save(). So I am getting the original number (708) 555-1212 in the database.
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>
What am I missing here?
Upvotes: 0
Views: 2566
Reputation: 3290
Made an edit: I realise that instead of overriding save
, we should instead clean/validate the phone number by using custom validation:
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"
Upvotes: 1