Summary of probelm: I have a file with all zip codes in the US, the file is in the format "ZIP,LATITUDE,LONGITUDE\n' I would like to save each line as a model instance of:
class ZipCode(models.Model):
zip_code = models.CharField(max_length=7)
latitude = models.DecimalField(decimal_places=6, max_digits =12)
longitude = models.DecimalField(decimal_places=6, max_digits =12)
without having to enter each manually by hand as this would take forever.
My attempt at a solution: Writing a view to handle this one time task does not seem like the best way to do this, but it is all I could think of, so I tried the following:
def update_zipcodes(request):
zip_code_file = open('zip_codes.txt')
#lists to hold zip code, longitude and latitude values:
zip_codes = []
latitude = []
longitude = []
for line in zip_code_file.readlines():
#example line "00601,18.180555, -66.749961"
zipcode, lat, lng = line.strip().split(',')
zip_codes.append(zipcode)
latitude.append(lat)
longitude.append(lng)
#convert lat and long to floats
latitude = [float(i) for i in latitude]
longitude = [float(i) for i in longitude]
counter = 0
for item in zip_codes:
zip_code_object = ZipCode(zip_code=zip_codes[counter],latitude=latitude[counter],longitude=longitude[counter])
zip_code_object.save()
counter= counter+1
return HttpResponse('working')
and it returned cannot find file 'zip_codes.txt'
even though I put this file in the same folder as views. Clearly I don't know how to accomplish the goal at hand. Is there anyway to go about connecting to my database and uploading the values as specified? (original values can be seen at https://gist.githubusercontent.com/erichurst/7882666/raw/5bdc46db47d9515269ab12ed6fb2850377fd869e/US%2520Zip%2520Codes%2520from%25202013%2520Government%2520Data , I copied and pasted this into zip_codes.txt)