Reputation: 11
I'm trying to import an excel file into my django project and create a Client object with the excel's data.
this is my Client model:
class Client(models.Model):
client = models.CharField(max_length=255, null=False)
name = models.CharField(max_length=255, blank=True, null=True)
surname = models.CharField(max_length=255, blank=True, null=True)
email = models.EmailField(blank=True, null=True)
phone = PhoneNumberField(blank=True, null=True)
i implemented this function to import the file:
import phonenumbers
def import_proj_excel(request):
if request.method == 'POST':
client_resource = ClientResource()
dataset = Dataset()
file = request.FILES['prog-file']
if not file.name.endswith('xlsx'):
messages.info(request, 'invalid format')
return render(request, 'excel.html')
imported_data = dataset.load(file.read(), format='xlsx')
for data in imported_data:
if data[1] is None or data[2] is None or data[3] is None or data[4] is None or data[4] is None or data[5] is None:
d1 = data[1]
d2 = data[2]
d3 = data[3]
d4 = data[4]
d5 = data[5]
if d1 is None:
d1 = ""
elif d2 is None:
d2 = ""
elif d3 is None:
d3 = ""
elif d4 is None:
d4 = ""
elif d5 is None:
d5 = str(data[5])
d5 = ""
value = Cliente(
data[0],
d1,
d2,
d3,
d4,
d5,
)
else:
phone = phonemubers(data[5])
print(type(phone))
value = Client(
data[0],
data[1],
data[2],
data[3],
data[4],
phone,
)
value.save()
return render(request, 'excel.html')
data[0] is the id
data[1] is client
data[2] is name
data[3] is surname
data[4] is email
data[5] is phone number
i did:
if data[1] is None or data[2] is None or data[3] is None or data[4] is None or data[4] is None or data[5] is None:
because when one of the field in the excel is empty I don't want to display in the object field None, but I want an empty string.
Anyway I get the error: Can't convert int to PhoneNumber.
raise TypeError("Can't convert %s to PhoneNumber." % type(value).name)
does anyone know how to solve this?
Upvotes: 1
Views: 2018
Reputation: 544
It looks like the phone number you're trying to insert is invalid. This could be due to the phone number formatting not matching the region you've designated (if you've designated a region) or the phone numbers not being formatted as a phone number instance (ex. '+41524204242') Explained here: https://pypi.org/project/django-phonenumber-field/
You can see the validation attempts, including the error you're seeing here:
It's hard to say without seeing the data in your Excel file but my guess is that the phone numbers in your Excel file aren't formatted the way the Phone Number Field is expecting them.
Upvotes: 1