2👍
Your validation looks correct to me, but you’re doing two things wrong:
- Rename the method to
clean_phone_number()
instead ofclean_phone
. The field isphone_number
notphone
. - Change the field to a
CharField
instead ofIntegerField
(too restrictive for many users) andreturn z.national_number
instead ofphone_number
, that way it’s returning the correctly cleaned number before saving. Or whatever format you want to store it in.
1👍
Set a field with "PhoneNumberField()" in "models.py":
# "models.py"
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
class MyModel(models.Model):
phone = PhoneNumberField()
Then, assign the widget "PhoneNumberPrefixWidget()" to the field with an initial country code like initial=’US’ in a custom form and assign the custom form to the admin as shown below. *Initial country code must be uppercase:
# "admin.py"
from django.contrib import admin
from .models import Contact
from django import forms
from phonenumber_field.widgets import PhoneNumberPrefixWidget
class ContactForm(forms.ModelForm):
class Meta:
widgets = { # Here
'phone': PhoneNumberPrefixWidget(initial='US'),
}
@admin.register(Contact)
class ContactAdmin(admin.ModelAdmin):
form = ContactForm
Now, with the initial country code "US" selected, the field for a phone number is created as shown below so that users don’t need to select a country code by themselves:
- [Django]-Django admin shows models name with extra "s" at the end
- [Django]-Copy a abstract model to another instance?
- [Django]-Why does this Django form complain "this field is required" for an image field?
- [Django]-Managing a pool of connections to a hosted Elastic Search provider
- [Django]-Sudo /etc/init.d/celeryd start generates a "Unknown command: 'celeryd_multi'"
0👍
I am not entirely familiar with these packages but after having a look at the repo code behind them it seems like you could just set the region
attribute on the PhoneNumberField
and keep inheriting all of its validation features and prevent the need for users to type in their region?
Something like this?
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
# Does this not work for your case?
phone_number = PhoneNumberField(region="SG")
class Meta:
model = User
fields = ['username', 'email', 'phone_number']
def clean_email(self):
email = self.cleaned_data.get("email")
if not validate_email(email, verify=True):
raise forms.ValidationError("Invalid email")
return email
- [Django]-Setting current user on django vanilla CreateView
- [Django]-Django – login required for POST but not GET?
- [Django]-How to run python script inside django project?
- [Django]-Django: Values_list returns id from choice field instead of name