I am writing a Django view which takes an attached csv file and reads it into the db:
views.py:
def climate_upload(request):
...
if form.is_valid(): # All validation rules pass
file = request.FILES['attach']
for line in file:
line = line.split(';')
report = Site1()
...
# These fields values be empty, integer or float
report.mean_air_temp = float(line[4])
report.min_air_temp = float(line[5])
report.max_air_temp = float(line[6])
report.sea_temp = float(line[7])
report.mean_rel_hum = float(line[8])
report.precipitation = float(line[9])
report.save()
file.close()
I understand that this is pretty crude code, but if I run this and one of the fields is empty (”) I get a ValueError could not convert string to float:.
I can do this for each field:
try:
report.mean_air_temp = float(line[4])
except(ValueError):
report.mean_air_temp = None
Which gives me the required results, but does not seem so robust/ elegant.
I would appreciate any guidance as to how to handle this code block.
Wrap the conversion to float in a function call.
or