Commits

Anonymous committed 81aeaea

Add templates for shape upload and fix tabs in python forms and views

Comments (0)

Files changed (5)

     #epsg = forms.IntegerField()
     
     def clean_file_obj(self):
-      f = self.cleaned_data['file_obj']
-      valid_shp, error = self.validate(f)
-      if not valid_shp:
-        raise ValidationError("A problem occured: %s" % error)
+        f = self.cleaned_data['file_obj']
+        valid_shp, error = self.validate(f)
+        if not valid_shp:
+            raise ValidationError("A problem occured: %s" % error)
 
     def handle(self,uploaded_file):
-      downloaded_file = '%s/%s' % (settings.SHP_UPLOAD_DIR, uploaded_file)
-      destination = open(downloaded_file, 'wb+')
-      for chunk in uploaded_file.chunks():
-          destination.write(chunk)
-      destination.close()        
+        downloaded_file = '%s/%s' % (settings.SHP_UPLOAD_DIR, uploaded_file)
+        destination = open(downloaded_file, 'wb+')
+        for chunk in uploaded_file.chunks():
+            destination.write(chunk)
+        destination.close()        
 
     def zip_check(self, ext, zip_file):
-      if not True in [info.filename.endswith('shp') for info in zip_file.infolist()]:
-        return False
-      return True
+        if not True in [info.filename.endswith('shp') for info in zip_file.infolist()]:
+            return False
+        return True
       
     def validate(self,uploaded_file):
-      tmp = tempfile.NamedTemporaryFile(suffix='.shp', mode = 'w')
-      tmp_dir = tempfile.gettempdir()
-      destination = open(tmp.name, 'wb+')
-      for chunk in uploaded_file.chunks():
-          destination.write(chunk)
-      destination.close()
-      if not zipfile.is_zipfile(tmp.name):
-        return False, 'That file is not a valid Zip Archive'
-      else:
-        zfile = zipfile.ZipFile(tmp.name)
+        tmp = tempfile.NamedTemporaryFile(suffix='.shp', mode = 'w')
+        tmp_dir = tempfile.gettempdir()
+        destination = open(tmp.name, 'wb+')
+        for chunk in uploaded_file.chunks():
+            destination.write(chunk)
+        destination.close()
+        if not zipfile.is_zipfile(tmp.name):
+            return False, 'That file is not a valid Zip Archive'
+        else:
+            zfile = zipfile.ZipFile(tmp.name)
         if not self.zip_check('shp', zfile):
-          return False, 'Found Zip Archive but no file with a .shp extension found inside.'
+            return False, 'Found Zip Archive but no file with a .shp extension found inside.'
         elif not self.zip_check('prj', zfile):
-          return False, 'You must supply a .prj file with the Shapefile to indicate the projection.'
+            return False, 'You must supply a .prj file with the Shapefile to indicate the projection.'
         elif not self.zip_check('dbf', zfile):
-          return False, 'You must supply a .dbf file with the Shapefile to supply attribute data.'
+            return False, 'You must supply a .dbf file with the Shapefile to supply attribute data.'
         elif not self.zip_check('shx', zfile):
-          return False, 'You must supply a .shx file for the Shapefile to have a valid index.'
+            return False, 'You must supply a .shx file for the Shapefile to have a valid index.'
         else:
-          for info in zfile.infolist():
-            data = zfile.read(info.filename)
-            shp_part = '%s%s' % (tmp_dir, info.filename)
-            fout = open(shp_part, "wb")
-            fout.write(data)
-            fout.close()
-            # http://code.djangoproject.com/wiki/GeoDjangoExtras#DataSource
-          ds_name = zfile.infolist()[0].filename.split('.')[0]
-          ds = DataSource('%s%s.shp' % (tmp_dir, ds_name))
-          layer = ds[0]
-          if layer.test_capability('RandomRead'):
+            for info in zfile.infolist():
+                data = zfile.read(info.filename)
+                shp_part = '%s%s' % (tmp_dir, info.filename)
+                fout = open(shp_part, "wb")
+                fout.write(data)
+                fout.close()
+                # http://code.djangoproject.com/wiki/GeoDjangoExtras#DataSource
+        ds_name = zfile.infolist()[0].filename.split('.')[0]
+        ds = DataSource('%s%s.shp' % (tmp_dir, ds_name))
+        layer = ds[0]
+        if layer.test_capability('RandomRead'):
             if ds._driver.__str__() == 'ESRI Shapefile':
-              return True, None
+                return True, None
             else:
-              return False, "Sorry, we've experienced a problem on our server. Please try again later."
-          else:
-              return False, 'Cannot read the shapefile, data is corrupted inside the zip, please try to upload again' 
+                return False, "Sorry, we've experienced a problem on our server. Please try again later."
+        else:
+            return False, 'Cannot read the shapefile, data is corrupted inside the zip, please try to upload again' 

shapes/templates/base.html

+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<html lang="en">
+<head>
+  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+  <title>{% block title %}{% endblock %}</title>
+</head>
+<body>
+  {% block content %}{% endblock %}
+</body>
+</html>

shapes/templates/upload.html

+{% extends "base.html" %}
+
+{% load i18n %}
+
+{% block content %}
+    {% if form.errors %}
+    <p class="errorlist">{% trans "Sorry there are corrections needed in your form below:" %} {{ form.non_field_errors }}</p>
+    {% endif %}
+    {% if form.is_multipart %}
+    <form enctype="multipart/form-data" method="post" action=".">
+    {% else %}
+    <form method="post" action=".">
+   {% endif %}
+   {{ form.as_p }}
+   <input type="submit" value="Upload your Document" />
+   </form>
+{% endblock %}

shapes/templates/uploaded.html

+{% extends "base.html" %}
+
+{% load i18n %}
+
+{% block title %}{% trans "Upload Complete" %}{% endblock %}
+
+{% block content %}
+<h1>{% trans "Thanks" %}</h1>
+<p>{% trans "Your upload was successful" %}</p>
+{% endblock %}
+{% block login %}
+<a href="/"> {% trans "Return to homepage." %}</a>
+{% endblock %}

shapes/views/export.py

         self.proj_transform = proj_transform
         self.mimetype = mimetype
         self.file_name = file_name
-    
+
     def __call__(self):
         """
         """
         
         if len(geo_fields) > 1:
             if not self.geo_field:
-              raise ValueError("More than one geodjango geometry field found, please specify which to use by name. Available fields are: '%s'" % geo_fields_names)
+                raise ValueError("More than one geodjango geometry field found, please specify which to use by name. Available fields are: '%s'" % geo_fields_names)
             else:
-              geo_field_by_name = [fld for fld in geo_fields if fld.name == self.geo_field]
-              if not geo_field_by_name:
-                raise ValueError("Geodjango geometry field not found with the name '%s', fields available are: '%s'" % (self.geo_field,geo_fields_names))
-              else:
-                geo_field = geo_field_by_name[0]
+                geo_field_by_name = [fld for fld in geo_fields if fld.name == self.geo_field]
+                if not geo_field_by_name:
+                    raise ValueError("Geodjango geometry field not found with the name '%s', fields available are: '%s'" % (self.geo_field,geo_fields_names))
+                else:
+                    geo_field = geo_field_by_name[0]
         elif geo_fields:
             geo_field = geo_fields[0]
         else:
         
         # If true we're going to reproject later on 
         if self.proj_transform:
-          srs = SpatialReference(self.proj_transform)
+            srs = SpatialReference(self.proj_transform)
         
         # Creating the layer
         layer = ogr.OGR_DS_CreateLayer(ds,os.path.basename(tmp.name), srs._ptr, ogr_type, None)
         # Create the fields
         # Todo: control field order as param
         for field in attributes:
-          fld = ogr.OGR_Fld_Create(str(field.name), 4)
-          added = ogr.OGR_L_CreateField(layer, fld, 0)
-          check_err(added) 
+            fld = ogr.OGR_Fld_Create(str(field.name), 4)
+            added = ogr.OGR_L_CreateField(layer, fld, 0)
+            check_err(added) 
         
         # Getting the Layer feature definition.
         feature_def = ogr.OGR_L_GetLayerDefn(layer) 
             
             idx = 0
             for field in attributes:
-              value = getattr(item,field.name)
-              try:
-                string_value = str(value)
-              except UnicodeEncodeError, E:
-                # pass for now....
-                # http://trac.osgeo.org/gdal/ticket/882
-                string_value = ''
-              ogr.OGR_F_SetFieldString(feat, idx, string_value)
-              idx += 1
+                value = getattr(item,field.name)
+                try:
+                    string_value = str(value)
+                except UnicodeEncodeError, E:
+                    # pass for now....
+                    # http://trac.osgeo.org/gdal/ticket/882
+                    string_value = ''
+                ogr.OGR_F_SetFieldString(feat, idx, string_value)
+                idx += 1
               
             # Transforming & setting the geometry
             geom = getattr(item,geo_field.name)
             # to match the shapefiles projection 'to-be'
             
             if geom:
-              if self.proj_transform:
-                geom.transform(self.proj_transform)
-              ogr_geom = OGRGeometry(geom.wkt,srs)
-              # create the geometry
-              check_err(ogr.OGR_F_SetGeometry(feat, ogr_geom._ptr))
+                if self.proj_transform:
+                    geom.transform(self.proj_transform)
+                ogr_geom = OGRGeometry(geom.wkt,srs)
+                # create the geometry
+                check_err(ogr.OGR_F_SetGeometry(feat, ogr_geom._ptr))
             else:
-              # Case where geometry object is not found because of null value for field
-              # effectively looses whole record in shapefile if geometry does not exist
-              pass
+                # Case where geometry object is not found because of null value for field
+                # effectively looses whole record in shapefile if geometry does not exist
+                pass
             
             
             # creat the feature in the layer.
         zip = zipfile.ZipFile(buffer, 'w', zipfile.ZIP_DEFLATED)
         files = ['shp','shx','prj','dbf']
         for item in files:
-          filename= '%s.%s' % (tmp.name.strip('.shp'), item)
-          zip.write(filename, arcname='%s.%s' % (self.file_name.rstrip('.shp'), item))
+            filename= '%s.%s' % (tmp.name.strip('.shp'), item)
+            zip.write(filename, arcname='%s.%s' % (self.file_name.rstrip('.shp'), item))
         if self.readme:
-          zip.writestr('README.txt',self.readme)
+            zip.writestr('README.txt',self.readme)
         zip.close()
         buffer.flush()
         zip_stream = buffer.getvalue()