Skip to content

Instantly share code, notes, and snippets.

@cesandoval
Created August 8, 2012 19:10
Show Gist options
  • Save cesandoval/3297717 to your computer and use it in GitHub Desktop.
Save cesandoval/3297717 to your computer and use it in GitHub Desktop.
web finches updates
#From models.py
shpTypeDict = {
"0":"Null Shape",
"1":"Point",
"3":"Polyline",
"5":"Polygon",
"8":"MultiPoint",
"11":"PointZ",
"13":"PolylineZ",
"15":"PolygonZ",
"18":"MultiPointZ",
"21":"PointM",
"23":"PolylineM",
"25":"PolygonM",
"28":"MultiPointM",
"31":"MultiPatch"
}
class DataFile(Dated):
"""Data files represent individual file uploads.
They are used to construct DataLayers.
"""
file = models.FileField(upload_to=get_upload_path)
upload = models.ForeignKey('UploadEvent', null=True, blank=True)
def get_upload_path(self, filename):
return 'uploads/%s/%s' % (self.upload.user.username, filename)
def __unicode__(self):
return "DataFile: %s" % self.file.url
def get_layer_data(self):
data = {}
f = self.file
zip_file = zipfile.ZipFile(f)
contents = zip_file.namelist()
proj = [n for n in contents if '.prj' in n]
if proj:
# guess the srs
proj_text = zip_file.open( proj[0] ).read()
data['notes'] = proj_text
data['srs'] = ''
else:
data['srs'] = ''
# give a default name and geometry type
basename = os.path.splitext(contents[0])[0]
extract = zip_file.extractall()
shp = shapefile.Reader(basename).shapes()
geometry_type = shpTypeDict[str(shp[3].shapeType)]
data['name'] = basename
data['geometry_type'] = geometry_type
f.close()
return data
#From views.py
@login_required
def review(request):
"""A view for uploading new data.
"""
user=User.objects.get(username='carlos')
if request.method == 'POST': # someone is giving us data
formset = LayerReviewFormSet(request.POST)
if formset.is_valid():
for form in formset:
srs = form.cleaned_data['srs']
layer = DataLayer(srs = srs)
layer = form.save(commit=False)
layer.save() #keep getting errors here... null value in column "author_id" violates not-null constraint
else: # we are asking them to review data
# get the last upload of this user
upload = UploadEvent.objects.filter(user=user).order_by('-date')[0]
data_files = DataFile.objects.filter(upload=upload)
layer_data = [ f.get_layer_data() for f in data_files ]
formset = LayerReviewFormSet( initial=layer_data )
@bengolder
Copy link

It would be a bit simpler to just use the gdal api built into django for reading the shapefiles:

@bengolder
Copy link

Also, you'll might need to add a line above layer.save that says somethiing to the effect of:

layer.author = request.user

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment